添加带有默认组件的新jpanel

时间:2012-10-11 03:34:15

标签: java swing jpanel jtabbedpane copying

每当我点击“添加”按钮时,任何人都可以告诉我如何在jtabbedPane中添加面板。它就像google chrome new tab.But就是,生成的面板必须包含一些默认组件。谢谢预先。

1 个答案:

答案 0 :(得分:1)

请参阅下面的代码。它告诉你如何做你需要的。

public class DemoApp {
    private JTabbedPane tabPane = new JTabbedPane();

    public DemoApp() {
        initComponents();
    }

    private void initComponents() {
        JFrame frame = new JFrame("Test");
        frame.setSize(500, 400);
        frame.setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        frame.getContentPane().add(panel);

        JButton btn = new JButton("Add panel");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int index = tabPane.getTabCount() + 1;
                JPanel newPanel = new JPanel();
                newPanel.setLayout(new FlowLayout());
                newPanel.add(new JLabel("Panel " + index));
                tabPane.addTab("Tab " + index, newPanel);
            }
        });
        panel.add(tabPane, BorderLayout.CENTER);
        panel.add(btn, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new DemoApp();
    }
}