Listening for action on internal JPanel from a JFrame
I have a JFrame that has a BottomPanel (a class I made that extends JPanel) inside it. And inside that JPanel is another JPanel called DicePanel(that again extends JPanel).
In DicePanel there is a button called 'End Turn' that when clic开发者_JS百科ked should end the players current turn for the board game the program is based on. I want to somehow listen for the buttonClicked event from DicePanel from inside my JFrame.
How do I do this?
Edit: Right now I have
for (Player p : f.playerList) {
int diceRoll = dice.roll();
System.out.println(p.move(diceRoll));
System.out.println(p.getCurrentCell());
System.out.println(diceRoll);
f.bottomPanel.dice.setDice(dice.getDice1(), dice.getDice2());
while (true) {
try {
break;
System.out.println("Waiting");
Thread.sleep(2000);
} catch (Exception e) {
}
}
}
Why?
I mean, you could probably do it by defining the button in your JFrame, and passing it along until you can place it in the DicePanel, but why do you need to add a listener in the JFrame in the first place?
You can use setDefaultButton()
, "which will be activated when a UI-defined activation event (typically the Enter key) occurs in the root pane regardless of whether or not the button has keyboard focus."
JFrame f = new JFrame("Dice Game");
JButton b = new JButton("End Turn");
f.getRootPane().setDefaultButton(b);
Here's a very simple example that suggests how you might structure your game to avoid an infinite loop without resorting to multiple threads.
As an aside, it's a bad idea to catch an exception with out a least some output, e.g. e.printStackTrace()
.
精彩评论