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:
package testcardlayout; import java.awt.CardLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; 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(); } }
package testcardlayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; public class sim extends JPanel { JButton simknop; public sim() { simknop = new JButton("simknop"); this.add(simknop); this.setBackground(Color.black); } }
package testcardlayout; import java.awt.Color; import javax.swing.JButton; import javax.swing.JPanel; 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 appreaciated!
Thank you in advance