开发者

Updating JLabel with value

开发者 https://www.devze.com 2023-01-27 02:14 出处:网络
Each time the user presses a button a counter amountWrongGuessed gets incremented by 1. (works correctly with testing with System.prinln)

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开发者_StackOverflow中文版.setText(String.valueOf(hg.getAmountGuessed()));
}/*updateComponents*/


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


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号