简体   繁体   中英

How to switch between JPanels in CardLayout?

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 JPanel s - 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?

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() {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM