CardLayout, switch between JPanels by ButtonClick

2019-02-25 00:06发布

问题:

I want to switch between JPanels by clicking buttons on the JPanels.

For example: I have a JPanel sim with a JButton simknop and a JPanel help with JButton helpknop I want to switch between these 2 JPanels by clicking the buttons. When I click JButton simknop JPanel help should appear and when I click JButton help JPanel sim should appear.

Below you can find the different classes:

main.java

public class main extends JFrame
{

    JPanel cards;
    sim sim;
    help help;

    public main()
    {
        this.setSize(1024,768);
        //this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Crazy Bombardement");
        this.setLocation(800, 100);//standaard in de hoek van het scherm

        cards = new JPanel();
        cards.setLayout(new CardLayout());
        sim = new sim();
        help = new help();

        cards.add(sim, "SIM");
        cards.add(help, "HELP");    

        this.add(cards);
        this.setVisible(true);
    }

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

sim.java

public class sim extends JPanel
{
    JButton simknop;

    public sim()
    {
        simknop = new JButton("simknop");
        this.add(simknop);
        this.setBackground(Color.black);
    }

}

help.java

public class help extends JPanel
{
    JButton helpknop;

    public help()
    {
        helpknop = new JButton("helpknop");
        this.add(helpknop);
        this.setBackground(Color.red);
    }

I want to use CardLayout for this but I can't figure out how to make it work for it to listen to different ActionListeners.

Any help is greatly appreciated!

回答1:

1) The buttons should not be on each panel in the CardLayout. They need to be on another external panel that is always visible, regardless of which card is showing on the card panel.

2) Once your buttons are located correctly, you would add an ActionListener to each, whose actionPerformed method would look something like (using SIM button as an example):

CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, "SIM");

Further reading: How To Use CardLayout

EDIT: In theory, you could have the buttons directly on the card panels, but it would be the opposite button on each panel (i.e., the SIM button would be on the Help panel, and vice versa).