Tonz
Tonz

Reputation: 129

Updating JLabel with value

Each time the user presses a button a counter amountWrongGuessed gets incremented by 1. (works correctly with testing with System.prinln)

But how exactly do i get this to update in my label each time i press the button?

I have made a property that returns this value.

 public int getAmountGuessed(){
    return amountGuessed;
}

Next i try to get the value of the label, but the value always remains at 0.

lblAmountGuessDisplay = new JLabel(String.valueOf(hg.getAmountGuessed()));


private void UpdateComponents()
{
      lblAmountGuessDisplay.setText(String.valueOf(hg.getAmountGuessed()));
}/*updateComponents*/

Upvotes: 1

Views: 10538

Answers (4)

akf
akf

Reputation: 39485

You need to add an ActionListener to your button. When the ActionListener is notified that the button is pressed, you can increment the counter and update the JLabel. The actionPerformed method will be triggered in the EDT, so you should be ok with threading.

lblAmountGuessDisplay.addActionListener( new ActionListener() {
       public void actionPerformed(ActionEvent ae) {
            hg.incrementAmountGuessed();
            lblAmountGuessDisplay.setText(String.valueOf(hg.getAmountGuessed()));
       }
} 

You will probably need to implement the incrementAmountGuessed method (which may be the root of your problem in the first place).

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

I agree with Fredrick -- that you've not posted enough information for your question to be answerable and that it may be a reference issue -- that the JLabel you are changing is not the one that is displayed in the program. If you post more code, we'll have a better chance of giving your a decent answer. Also, this doesn't smell like a threading issue.

Upvotes: 1

npinti
npinti

Reputation: 52185

It might be a threading issue. Please take a look here.

Upvotes: 1

trashgod
trashgod

Reputation: 205785

This example shows one way to update a label each time a button is clicked.

Upvotes: 1

Related Questions