0

对于 Java GUI 作业额外的功劳,我正在尝试将几个面板添加到 JTabbedPane。实际上,它们是 JFrame,但我只是更改为扩展 JPanel 而不是 JFrame,并删除了 main()。无论如何,当我运行 main() 时,JTabbedPane 和两个面板都出现了,但是是分开的。我错过了什么?

   import javax.swing.*;

public class TabbedPane extends JFrame
{

    JPanel DayGui = new JPanel();
    JPanel OfficeAreaCalculator = new JPanel();
    JLabel firstLabel = new JLabel("First tabbed pane");
    JLabel secondLabel = new JLabel("Second tabbed pane");
    JTabbedPane tabbedPane = new JTabbedPane();

    // constructor
    public TabbedPane()
    {
        DayGui.add(firstLabel);
        OfficeAreaCalculator.add(secondLabel);

        tabbedPane.add("First Panel", DayGui);
        tabbedPane.add("Second Panel", OfficeAreaCalculator);
        add(tabbedPane);

    }

    public static void main(String[] args)
    {
        TabbedPane tab = new TabbedPane();
        tab.pack();
        tab.setVisible(true);
        JTabbedPane DayGui = new JTabbedPane();
        JTabbedPane OfficeAreaCalculator = new JTabbedPane();
        DayGui dg = new DayGui();
        OfficeAreaCalculator oac = new OfficeAreaCalculator();
    }
}
4

1 回答 1

2

您正在创建 2 对变量,用于引用要添加到的组件,JFrame但添加指向空白的组件JPanels。根据官方教程学习这段代码

public class TabbedPaneApp {

    private static void createAndShowGUI() {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTabbedPane firstPanel = new JTabbedPane();
        JTabbedPane secondPanel = new JTabbedPane();

        JLabel firstLabel = new JLabel("First tabbed pane");
        JLabel secondLabel = new JLabel("Second tabbed pane");

        JTabbedPane tabbedPane = new JTabbedPane() {
            public Dimension getPreferredSize() {
                return new Dimension(500, 400);
            };
        };

        firstPanel.add(firstLabel);
        secondPanel.add(secondLabel);

        tabbedPane.add("First Panel", firstPanel);
        tabbedPane.add("Second Panel", secondPanel);
        frame.add(tabbedPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
于 2013-09-29T22:32:32.167 回答