我可以通过Java中的Thread更改标签的文本吗? [英] Can I change the text of a label from a Thread in Java?
问题描述
我对这个论坛还有另一个问题.我正在用Java编写一个小型应用程序,其中有多个线程.我有两个不同类的两个线程.我有一个专用于定义所有JFrame组件的线程( thread1 ). (JPanels,JButton,ActionListeners等),在另一个线程( thread2 )中,我正在检查变量( v )是否等于某个值. ( 98 )当此变量确实更改为等于 98 时,该相同线程应该会更新JLabel. (现在我们将此标签称为 label .)事实并非如此.我做错了什么吗?我尝试为该类编写一个方法-声明所有JFrame组件-更改 label 的文本,但是当我从 thread2 调用此方法时,它不会更新标签.我尝试调用包含 thread1 的超类,但这似乎没有什么不同.另外,我一直在调用 repaint()方法,但这似乎无济于事.
I have another question for this forum. I am writing a small application with Java in which I have multiple Threads. I have two Threads that are in two different classes. I have one Thread (thread1) dedicated to defining all of the JFrame components. (JPanels, JButtons, ActionListeners, etc.) In another Thread, (thread2) I am checking for a variable (v) to equal a certain value. (98) When this variables does change to equal 98, that same thread is supposed to update a JLabel. (Let's call this label label for now.) It does not. Is there something I am doing wrong. I have tried writing a method for the class - that declares all of the JFrame components - that changes the text of label, but when I call this method from thread2 it does not update the label. I have tried calling a super class containing thread1, but that did not seem to make a difference. Also, I have been calling the repaint() method, but that does not seem to help.
请让我知道如何从两个不同的线程更新这些JLabel.
Please let me know what I can do to update these JLabels from the two different Threads.
预先感谢, 〜雷恩
Thanks in advance, ~Rane
代码:
Class1:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("V does not equal 98 Yet...");
Thread thread1 = new Thread(){
public void run(){
panel.add(label);
frame.add(panel);
System.out.println("Components added!");
}
});
public void setLabelText(String text){
label.setText(text);
}
Class1 = 2:
Class1=2:
v = 0;
Thread thread2 = new Thread(){
public void run(){
while(v < 98){
System.out.println("V equals -" + v + "-.");
v ++;
}
Class1 otherClass = new Class1();
otherClass.label.setText("V is now equal to: " + v);
otherClass.repaint();
otherClass.setLabelText("V is now equal to: " + v);
otherClass.repaint();
}
});
推荐答案
Swing是不是线程安全的.我重复一遍:除了事件调度线程(EDT)之外,不要从任何线程调用Swing对象的任何方法. )
Swing is not thread-safe. I repeat: do not call any methods on Swing objects from any threads other than the Event Dispatch Thread (EDT)
如果要从多个不同的线程获取事件,并且希望它们直接影响Swing对象,则应使用:
If you are getting events from multiple different threads and you want to have them directly affect Swing objects, you should use:
// Note you must use final method arguments to be available inside an anonymous class
private void changeJLabel(final JLabel label, final String text) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
myLabel.setText(text);
}
});
}
这篇关于我可以通过Java中的Thread更改标签的文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!