使用JTabbedPane时,Java / Swing GUI不会刷新

时间:2013-10-06 08:06:41

标签: java swing user-interface jtabbedpane

所以我尝试使用JTabbedPane,我开始使用一个简单的程序,它显示三个选项卡,每个选项卡都有一个不同的标签。这是代码:

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);
    }
}

我在启动应用程序时发现了一个奇怪的行为:如果您在第三个选项卡的面板上单击第二个选项卡之前的第三个选项卡(因此显示的选项卡的顺序为1> 3> 2)将会显示第二个标签的标签,而不是第三个标签!然后,如果您移动到第二个选项卡,然后移动到第三个选项卡,一切都会正常。解释比检查更难解释。那么我该如何解决这个问题呢?

0 个答案:

没有答案