JTabbedPane Example
This JTabbedPane example is created with two tabs, each of which has a label and a container. Each of JTabbedPane's containers will usually have its own specific purpose and its own set of controls. When a user selects one of the JTabbedPane's tabs, its container with controls is displayed.
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
// JTabbedPane Example
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
class JTabbedPaneExample {
public static void main(String[] args) {
JPanel p0 = new JPanel(), p1 = new JPanel();
p0.setBackground(Color.cyan);
for(int i=0; i<5; i++) p0.add(new JButton("button "+i));
p1.setBackground(Color.blue);
for(int i=0; i<5; i++) p1.add(new JLabel("label "+i));
final JTabbedPane jtp = new JTabbedPane();
jtp.addTab("cyan",p0);
jtp.addTab("blue",p1);
jtp.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println("tabIndex="+jtp.getSelectedIndex());
}
});
JFrame frame = new JFrame();
Container cp = frame.getContentPane();
cp.add(jtp);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
20-24 A ChangeListener is added to the JTabbedPane although this is often unnecessary. The user action of selecting a tab brings the appropriate JTabbedPane container into focus and user interaction with the data and controls on it takes place without the necessity for the program to be aware of the user's tabbing.
