I've checked on the other threads here and haven't found a solution.
1) The JFrame is setVisible(true).
2) What does this mean: "I wonder if your problem is a concurrency issue, that you are doing a long-running process on the Swing event thread and that this is preventing your label from updating its text." I read that somewhere else.
3) I haven't initialized multiple times the JPanel that contains the label.
EDIT:
4) updateTurn is called from the JPanel that contains TrackingPanel
(i.e. gamePanel
). I call the method changeTurns();
and here's the code for that:
public void changeTurns() {
if(turnPlayer == playerX)
turnPlayer = playerO;
else
turnPlayer = playerX;
trackingPanel.updateTurn();
}
Here's the relevant code in full:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrackingPanel extends JPanel{
/*TURN STUFF*/
private JPanel turnPanel; //turns panel to keep track of whose turn it is
private JLabel turnLabel;
private String turn;
/*OTHER*/
private GamePanel gamePanel;
public TrackingPanel( GamePanel gamePan ) {
setLayout( new GridLayout(1,4) );
setBorder(BorderFactory.createMatteBorder(2,2,4,2,Color.BLACK));
gamePanel = gamePan;
/*THIS PANEL DISPLAYS THE TEXT*/
turnPanel = new JPanel( new GridLayout(2,1) );
turn = gamePanel.getPlayerTurn().getLetter();
turnLabel = new JLabel(" Player " + turn + "'s turn");
add( turnPanel);
}//end constructor
/*THIS IS WHERE THINGS GO WRONG*/
public void updateTurn() {
turn = gamePanel.getPlayerTurn().getLetter();
turnLabel.setText( " Player" + turn + "'s turn" );
System.out.println(turn);
}
}
Before updateTurn()
is called, turnLabel
says "PlayerX's turn". After, it should say "PlayerO's turn". By printing out turn
(I get the string 'O', instead of 'X'), I know that whats being displayed ("PlayerX's turn") is not what should be displayed ("PlayerO's turn").
Thanks in advance you smartypants!
EDIT. Tried giving SSCCE but don't know how to include image files. Sorry!
Try using this:
I've changed your code so that it doesn't require images, and now the turnLabel has been added. It is still too big, but it runs and shows some behaviors:
But interestingly, the turnLabel changes its text as it is supposed to in this example above. So now you must try to isolate your error as it may be in code left out. Perhaps it has something to do with concurrency as you mention in your question:
So perhaps you have a long running process that you've not shown us in the code above.
Also, your code has an over-use of static fields anti-pattern. Most of the fields that are static should not be static.
I would make sure that your method updateTurn() calls its code within Swing's thread using SwingUtilities.invokeLater(new Runnable()) method.