0

In the application I'm writing, I temporarily added a JLabel type field to the menu bar which displays which player's turn it is. Unfortunately, but despite many attempts, I am not able to refresh the player number (it should be Turn of Player 1 or Turn of Player 2).

I recently added an ActionListener, but it didn't help, maybe I'm doing something wrong?

Below are code snippets:

public class Bar extends JMenuBar implements ActionListener {
    (...)
    static boolean isPlayer1Move = movement.isPlayer1Move();
    static JLabel whichPlayer = new JLabel("[Turn of Player " + checkWhichPlayer(isPlayer1Move) + "]");

    public Bar() {
        (...)
    }

    public static int checkWhichPlayer(boolean isPlayer1Move) {
        return isPlayer1Move ? 1 : 2;
    }

    public void actionPerformed(ActionEvent event) {
        whichPlayer.setText("");

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String result = "[Turn of Player " + checkWhichPlayer(isPlayer1Move) + "]";
                whichPlayer.setText(result);
            }
        });
}

Here's my game:

State of new game.

State of new game

After a few moves, the Turn of Player 1 caption does not change.

After a few moves, the Turn of Player 1 caption does not change.

j.sadne
  • 39
  • 5
  • For better help sooner, [edit] to add a [mre]. – Andrew Thompson Apr 29 '22 at 06:23
  • BTW: 1) `SwingUtilities.invokeLater(new Runnable() ..` one place this is absolutely unnecessary is in an `actionPerformed` method. By definition and plan, it ***is*** being called on the Event Dispatch Thread. 2) I see an edit to add pictures.. cute, but they explain nothing that is not clear from the words above them. 3) **Where is that MRE?** – Andrew Thompson Apr 29 '22 at 06:41
  • 2
    _After a few moves, the Turn of Player 1 caption does not change._ Are you saying that, for the first few moves, the caption does change? – Abra Apr 29 '22 at 07:07

1 Answers1

0

From your snippet I cant see if the action listener is properly registered (what is he listening to?) But I think your problem relies in the fact that your isPlayerMove variable is a value not a reference and therefore does not update when movement.isPlayer1Move() updates. So your listener probable works fine, but the boolean remains true. If you are not familiar with call by value / reference take a look here: Is Java "pass-by-reference" or "pass-by-value"?

Eskapone
  • 301
  • 6