如何在applet中使用2个面板?

时间:2013-02-10 23:03:24

标签: java swing user-interface cardlayout

我正在努力研究如何在秋千中浏览多个面板。我想通过使用CardLayout来实现这一点,而不是使用玻璃面板,因为我已经阅读了它似乎这是这项工作的正确工具(但是,如果你不知道,请随时纠正我)。我写了一个测试用例几乎可以实现这个目标,但在2个方面都不尽如人意。它使用折旧的“show()”方法,而且在切换到第二张卡后,来自card1的按钮开始神秘地再次漂浮到表面!

public class test extends JPanel implements ActionListener{
    final static int extraWindowWidth = 100;
    JButton jbtnOne = new JButton("Button 1");
        JPanel cardPanel = new JPanel(new CardLayout());
        JPanel card1 = new JPanel();
        JPanel card2 = new JPanel();

    public void addComponentToPane(Container pane) {

        //Create the "cards".
        JPanel card1 = new JPanel() {
            public Dimension getPreferredSize() {
                Dimension size = super.getPreferredSize();
                size.width += extraWindowWidth;
                return size;
            }
        };


        card1.add(jbtnOne);
        card1.add(new JButton("Button 2"));
        card1.add(new JButton("Button 3"));     
        card2.add(new JTextField("TextField", 20));

        cardPanel.add(card1, "card1");
        cardPanel.add(card2, "card2");

        pane.add(cardPanel, BorderLayout.CENTER);
        jbtnOne.addActionListener(this);
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TabDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        test demo = new test();
        demo.addComponentToPane(frame.getContentPane());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if(e.getSource() ==  jbtnOne){
            System.out.println("HERE");
            card2.show();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

CardLayout正在管理组件,因此您需要在show而不是CardLayout上致电JPanel#show

CardLayout cardLayout = (CardLayout) cardPanel.getLayout();
cardLayout.show(cardPanel, "card2");

或者,在切换卡组件时,您也可以使用

cardLayout.next(cardPanel);