Java: CardLayout switching between cards

吃可爱长大的小学妹 提交于 2019-12-05 14:28:33

You need a reference to the CardLayout of the JFrame inside your panel classes. What you can do is pass the Frame to the JPanel classes as reference, then you can use the CardLayout of the Frame in those classes to show or next etc. Something like

public class MainMenu {
    private CardLayout layout;
    private Frame frame;

    public MainMenu(final Frame frame) {
         this.frame = frame;
         this.layout = (CardLayout)frame.getLayout();

         JButton buttonSingle = new JButton("Single");     
         buttonSingle.setAlignmentX(Component.CENTER_ALIGNMENT);
         buttonSingle.addActionListener(new ActionListener(){
             @Override
             public void actionPerformed(ActionEvent e) {
                 layout.show(frame, "single");
             }
         });
    }
}

When you create the MainPanel, you need to pass Frame.this to it, referencing the current Frame

MainMenu menuPanel = new MainMenu(Frame.this);

EDIT

I just noticed your swapView method. So instead of use the CardLayout directly in the panel class, you can actually just call swapView in the actionPerformed

frame.swapView("single");

Or better yet, as to not expose the Frame class, you can have the Frame class implement an interface say SwapInterface that has a method swapView you need to override. And pass the SwapInterface to the panel classes. Something like

public interface SwapInterface {
    public void swapView(String view);
}

public Frame extends JFrame implements SwapInterface {
    MainMenu mainPanel = new MainMenu(Frame.this);
    ....
    @Override
    public void swapView(String view) {
        cl.show(getContentPane(), view);
    }
}

public class MainMenu extends JPanel {
    private SwapInterface swap;

    public MainMenu(SwapInterface swap) {
        this.swap = swap;
        ...
        public void actionPerfomed(ActionEvent e) {
            swap.swapView("single");
        }

    }
}

Side Note

As HovercraftFullOfEels pointed out in his comment, you should make use of String contants for the String card values so there's no mistakes. Something like

private static final String SINGLE_CARD = "single";

Then in places where you use "single", use SINGLE_CARD instead

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