Hello everyone :)
I'm learning Java and I'm creating a pong game. There is something I don't understand how to do though. It's how do I make it so that when a button in one panel is pushed, it calls a method in another panel. Let me quickly explain the basics of my program so that question will make any sense:
I have a main class called Pong, which simply creates a frame and adds a panel called PongPanel.
public class PongPanel extends JPanel
{
public PongPanel()
{
setLayout (new BorderLayout());
setPreferredSize (new Dimension(400, 200));
game = new GamePanel();
ButtonPanel buttons = new ButtonPanel();
add(game, BorderLayout.CENTER);
add(buttons, BorderLayout.SOUTH);
}
}
The PongPanel, as you can see, creates two more panels, a GamePanel where all the game logic takes place, and a ButtonPanel, where buttons like "New game" and "Switch sides" are found. Inside the GamePanel there is a method called initalizeNewGame(). I want to call this method when the button "New Game" is pushed in the buttonpanel. How do I do that?
Here is the buttonpanel code, the problem is at the bottom:
public class ButtonPanel extends JPanel
{
private String buttonText = "New Game";
private JButton button;
public ButtonPanel()
{
button = new JButton(buttonText);
button.addActionListener(new ButtonListener());
add(button);
}
public void toggleButtonEnabled()
{
if (button.isEnabled())
button.setEnabled(false);
else
button.setEnabled(true);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (button.isEnabled())
//call initializeNewGame(); <<---- what to write here???
}
}
}
I've tried writing GamePanel.initializeNewGame(), game.initalizeNewGame(), to no avail, I seem to be missing something, is it out of scope? Should something somewhere be static? Please help me understand why it won't work or what I should do. Thank you in advance :)