How to switch between JPanels in CardLayout?

泄露秘密 提交于 2019-12-11 12:57:26

问题


I have two JPanels that I want to switch between when user clicks on them.

So I created a Window with a JFrame in it. Then I create a JPanel called cards and set its layout to CardLayout. Then I create two more JPanels - these are the panels that I want to switch between - and I add them to cards. I add mouseClicked event listeners and I add cardLayout.next(cards) so the switch will happen. It doesn't work.

Here's my code:

public class Window {
    private JFrame frame;
    private JPanel cards;
    private JPanel panel1;
    private JPanel panel2;
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Window window = new Window();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public Window() {
        initialize();
    }
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 790, 483);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        cards = new JPanel();
        cards.setLayout(new CardLayout());
        panel1 = new JPanel();
        panel1.setBackground(Color.BLACK);
        panel1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e){
                java.awt.Toolkit.getDefaultToolkit().beep(); //debug beep
                CardLayout cl = (CardLayout) cards.getLayout();
                cl.next(cards);
            }
        });

        panel2 = new JPanel();
        panel2.setBackground(Color.WHITE);
        panel1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e){
                CardLayout cl = (CardLayout) cards.getLayout();
                cl.next(cards);
            }
        });

        cards.add(panel1, "panel1");
        cards.add(panel2, "panel2");

        frame.getContentPane().add(cards);
    }

}

Why doesn't it work?


回答1:


You've added 2 MouseListeners to the same panel which effectively cancels out the call to CardLayout.next. Replace one of

panel1.addMouseListener(new MouseAdapter() {

with

panel2.addMouseListener(new MouseAdapter() {


来源:https://stackoverflow.com/questions/37092959/how-to-switch-between-jpanels-in-cardlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!