0

所以我尝试使用 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)将显示第二个选项卡的标签,而不是第三个!然后,如果您移动到第二个选项卡,然后在第三个选项卡上,一切都会好起来的。解释比检查更难。那么我该如何解决这个问题呢?

4

0 回答 0