用值更新 JLabel
每次用户按下按钮时,计数器 amountWrongGuessed
都会增加 1。(使用 System.prinln
进行测试时可以正常工作)
但是我到底如何在我的应用程序中更新它?每次按下按钮时都贴上标签?
我创建了一个返回该值的属性。
public int getAmountGuessed(){
return amountGuessed;
}
接下来我尝试获取标签的值,但该值始终保持为 0。
lblAmountGuessDisplay = new JLabel(String.valueOf(hg.getAmountGuessed()));
private void UpdateComponents()
{
lblAmountGuessDisplay.setText(String.valueOf(hg.getAmountGuessed()));
}/*updateComponents*/
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*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此示例展示了每次单击按钮时更新标签的一种方法。
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.
我同意 Fredrick 的观点——您没有发布足够的信息来回答您的问题,并且这可能是一个参考问题——您正在更改的 JLabel 不是程序中显示的 JLabel。如果您发布更多代码,我们将有更好的机会为您提供满意的答案。另外,这听起来不像是线程问题。
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.
您需要向按钮添加一个
ActionListener
。当ActionListener
收到按钮被按下的通知时,您可以增加计数器并更新JLabel
。actionPerformed
方法将在 EDT 中触发,因此您应该可以使用线程。您可能需要实现
incrementAmountGuessed
方法(这可能是问题的根源)。You need to add an
ActionListener
to your button. When theActionListener
is notified that the button is pressed, you can increment the counter and update theJLabel
. TheactionPerformed
method will be triggered in the EDT, so you should be ok with threading.You will probably need to implement the
incrementAmountGuessed
method (which may be the root of your problem in the first place).