So I was trying to use JTabbedPane and I started with a simple program, wich displays three tabs and for each tab a different label. Here is the code:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
public class JTableExample extends JFrame {
JTabbedPane tabs;
JTableExample(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
initTabs();
setVisible(true);
pack();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
}
public static void createAndShowUI() {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e1) {
}
}
break;
}
}
JTableExample gui = new JTableExample(null);
gui.setTitle(null);
}
public void initTabs() {
tabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
tabs.setPreferredSize(new Dimension(200, 100));
JPanel panel1 = new JPanel();
JLabel l1 = new JLabel("I'm a label");
tabs.addTab("tab1", panel1);
panel1.add(l1);
panel1.setVisible(true);
JPanel panel2 = new JPanel();
JLabel l2 = new JLabel("I'm another label!");
tabs.addTab("tab2", panel2);
panel2.add(l2);
panel2.setVisible(true);
JPanel panel3 = new JPanel();
tabs.addTab("tab3", panel3);
JLabel l3 = new JLabel("A Label");
panel3.add(l3);
l3.setVisible(true);
panel3.setVisible(true);
add(tabs);
tabs.setVisible(true);
}
}
I noticed a strange behaviour when starting the application: if you click on the third tab before the second tab (so the order of displayed tabs is 1 > 3 > 2) on the panel of the third tab will be shown the second tab's label, and not the third one! Then if you move to the second tab and then on the third, everything will be ok. It's harder to explain than to check. So how can I fix this issue?