So, I'm trying to make a basic functional menu for a simple game. I tried to do this by creating 2 JPanels, one for the actual game, and another for my menu.
What I'm trying to do is have a button on my Menu panel that when pressed, switches the JPanel being displayed in the parent JFrame from that of the menu to that of the actual game.
Here is my code:
class Menu extends JPanel
{
public Menu()
{
JButton startButton = new JButton("Start!");
startButton.addActionListener(new Listener());
add(startButton);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Container container = getParent();
Container previous = container;
System.out.println(getParent());
while (container != null)
{
previous = container;
container = container.getParent();
}
previous.setContentPane(new GamePanel());
}
}
}
As you can see, I created a Listener for my start button. Inside the listener, I used a while loop to get to the JFrame, via the getParent()
method. The program is getting the JFrame object, however it's not letting me call the setContentPane
method...
Does anyone know how to get this to work, or a better way to switch back and forth between a menu and game?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…