CardLayout,通过ButtonClick在JPanel之间切换

我想通过点击JPanels上的按钮在JPanel之间切换。

例如:我有一个带有JButton simknop的JPanel sim和带有JButton helpknop的JPanel帮助我想通过单击按钮在这两个JPanel之间切换。 当我点击JButton simknop时,应该出现JPanel帮助,当我点击JButton时,应该会出现JPanel sim。

您可以在下面找到不同的类:

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); } 

我想使用CardLayout,但是我无法弄清楚如何使它能够听到不同的ActionListeners。

任何帮助是极大的赞赏!

1)按钮不应位于CardLayout中的每个面板上。 它们需要位于另一个始终可见的外部面板上,无论卡面板上显示哪个卡。

2)正确定位按钮后,您可以为每个按钮添加一个ActionListener,其actionPerformed方法看起来像(使用SIM按钮作为示例):

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

进一步阅读: 如何使用CardLayout

编辑:理论上,您可以直接在卡面板上使用按钮,但它将是每个面板上的相反按钮(即,SIM按钮将位于“帮助”面板上,反之亦然)。