So I'm using cardLayout in one of my programs and I'm trying to make it so that when you click a button the next panel loads. I have a panelHolder class where the cardlayout is held and every time the button on the panel is pressed, it would call a method in the panelHolder class that depending on the button sets a certain boolean variable to true and calls repaint (where the panels are shown). For some reason my button isn't working and I can't seem to find out why. Can someone help me?
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.Arrays;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
public class SheetReader101 extends JFrame {
public SheetReader101(){
super("SheetReader101");
setSize(2000,1000);
setLocation(0,0);
setResizable(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
PanelHolder pg2 = new PanelHolder();
setContentPane(pg2);
setVisible(true);
}
public static void main(String[]args){
SheetReader101 z1 = new SheetReader101();
}
}
class PanelHolder extends JPanel { // HERE
CardLayout clayout = new CardLayout();
PianoGameContent x;
tutorial y;
boolean [] paneldecide;
PanelHolder() {
super();
y = new tutorial();
x = new PianoGameContent();
setLayout(clayout);
this.add("Tutorial", y);
this.add("FreePlay Mode", x);
paneldecide = new boolean[15];
}
public static void main(String[]args){
PanelHolder z1 = new PanelHolder();
z1.run();
}
public void run(){
layoutShower(0);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void layoutShower (int decide){
{
PianoGameContent y2 = new PianoGameContent();
PanelHolder.this.add("Piano", y2);
System.out.println("intro slide run");
if(decide == 1){
PanelHolder.this.add("Piano", y2);
System.out.println("testing11");
clayout.show(PanelHolder.this,"Piano");
}
}
}
}
I "suspect" that the core problem has to do with the original code you posted, where you're making a new instance of
PanelHolder
in your child view'sActionListener
and then are attempting to switch views, this new instance has no relationship to the instance that is on the screen.There are a few ways you can manage
CardLayout
, my preferred way is to use some kind of "navigation" controller which defines how navigation works, for example, you could have "next" and "previous" or "back", or you could define the actual views that can be displayed, ieshowMenuView
,showTutorialView
etc, depending on how much control you want to give your sub views.The following is a simple example which demonstrates the basic idea, it uses a
enum
to define the available views (as it has more meaning than0
,1
... and I don't need to remember the actual names of the views, the IDE can provide auto correct for that ;))I create and add each view up front when I create the
PanelHolder
, I also pass each view an instance of theNavigationController
, so they can interact with itTake a closer look at How to Use CardLayout for more details