Magazine
 

Tips & Tricks

 
javax.swing package can be used in Java. To create a tabbed pane, instantiate JTabbedPane,create components you wish it to display, and then add components to the tabbed pane using addTab() method.

Example Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTabbedPaneExample implements
ActionListener {
JFrame frame;
JTabbedPane tabPane;
JButton addTab;
ImageIcon close;
Dimension size;
int tabCounter = 0;
public static void main(String[] args) {
JTabbedPaneExample jtab = new
JTabbedPaneExample();
}
public JTabbedPaneExample() {
// Create a frame
frame = new JFrame();
// Create the tabbed pane.
tabPane = new JTabbedPane();
// Create a button to add a tab
addTab = new JButton(“Add Tab”);
addTab.addActionListener(this);
// Create an image icon to use as a
close button
close = new ImageIcon(“C:/
JAVAJAZZUP/tabClose.gif”);
size = new
Dimension(close.getIconWidth()+1,
close.getIconHeight()+1);
//Adding into frame
frame.add(tabPane,
BorderLayout.CENTER);

  public void actionPerformed(ActionEvent e)
{
JLabel label = null;
final JPanel panel = new JPanel();
// Create a panel to represent the tab
JPanel tab = new JPanel();
tab.setOpaque(false);
try{
String str =
JOptionPane.showInputDialog(null, “Enter Tab
Name : “, “JavaJazzUp”, 1);
if (str.length() == 0){
JOptionPane.showMessageDialog(null,
“Please Enter the Tab Name : “, “JavaJazzUp”,
1);
}
else if (str != null){
label = new JLabel(str);
}
else{
JOptionPane.showMessageDialog(null,
“You pressed cancel button.”, “JavaJazzUp”,
1);
}
JButton tabClose = new JButton(close);
tabClose.setPreferredSize(size);
tabClose.addActionListener(new
ActionListener() {
public void
actionPerformed(ActionEvent e) {
int tNum =
tabPane.indexOfComponent(panel);
tabPane.removeTabAt(tNum);
}
});
tab.add(label, BorderLayout.WEST);
tab.add(tabClose, BorderLayout.EAST);
tabPane.addTab(null, panel);
tabPane.setTabComponentAt(
tabPane.getTabCount()-1, tab);
}
catch(Exception ex){}
}
Nov 2007 | Java Jazz Up | 58
previous
index
next
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69   Download PDF