Reputation: 63
So I'm trying to make a basic program to learn more about java, and I'm having trouble switching screens. I wanted to have a display class that I could call in other classes to handle all the panels and such, and then make a class to build each panel. What I'm trying to do at the moment is use a button in my startmenu class to change from one panel to another using a method in the display class.
Here's the code in the startmenu
class:
public void actionPerformed(ActionEvent e)
{
display.switchPanel("Start");
}
And here is my display class:
public class Display { JFrame frame; StartMenu start = new StartMenu(); MainMenu main = new MainMenu(); JPanel panel = new JPanel(); JPanel startPanel = start.createPanel(); JPanel mainPanel = main.createPanel(); CardLayout card = new CardLayout(); BorderLayout border = new BorderLayout(); public void createDisplay() { frame = new JFrame("Insert Name"); frame.setPreferredSize(new Dimension(800,600)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(border); panel.add(startPanel); panel.add(mainPanel); mainPanel.setVisible(false); startPanel.setVisible(true); frame.add(panel); frame.pack(); frame.setVisible(true); frame.setResizable(false); } public void switchPanel(String x) { String p = x; if(p.equals("Start")) { mainPanel.setVisible(true); startPanel.setVisible(false); } } }
Upvotes: 4
Views: 758
Reputation: 347314
Use a CardLayout
, it's what it's designed for, for example...
public class Display {
public static final String START_VIEW = "start";
public static final String MAIN_VIEW = "main";
JFrame frame;
StartMenu start = new StartMenu();
MainMenu main = new MainMenu();
JPanel panel = new JPanel();
JPanel startPanel = start.createPanel();
JPanel mainPanel = main.createPanel();
CardLayout card = new CardLayout();
public void createDisplay() {
frame = new JFrame("Insert Name");
frame.setPreferredSize(new Dimension(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(card);
panel.add(startPanel, START_VIEW);
panel.add(mainPanel, MAIN_VIEW);
mainPanel.setVisible(false);
startPanel.setVisible(true);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
}
public void switchPanel(String x) {
card.show(panel, x);
}
}
Then you might use something like...
public void actionPerformed(ActionEvent e)
{
display.switchPanel(Display.START_VIEW);
}
to switch between the views
See How to Use CardLayout for more details
Upvotes: 4