views:

21

answers:

2

Hi, 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 clicked 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) {
        }
    }
}
A: 

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?

zigdon
Ok, so the game is running right and it is one Players turn. When the End Turn button is clicked I want to end its turn. Bascially I need to make a while loop that says 'while his turn is not over *wait* '. When the button is pressed I need to set a boolean or something to let the Turn() method know that his turn is over.
Sean
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){ } } }
Sean
But this just makes an infinite loop and the frame is not displayed (because the paint() method is never called by the system i guess beause of the loop). Maybe I need to make another thread - one for the Turn method and one for the GUI?
Sean
In general, it's a very good idea to have your GUI on a separate thread than your actual code - so that your main windows remain responsive while you do calculations in the background.
zigdon
A: 

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().

trashgod