[英]pass JFrame to a thread
I have a class that creates a JFrame. 我有一个创建JFrame的类。 When the start button is clicked, it calls my CoinCounterMechanism class.
单击开始按钮后,它将调用我的CoinCounterMechanism类。 This class contains the following Thread:
此类包含以下线程:
Thread consumer = new Thread("CONSUMER"){
public void run ()
{
Integer coin;
while (producerFlag)
try
{
coin = queue.take();
System.out.println("Coin received: " + coin);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
};
When this thread gets called from my other class, I need to pass it the JFrame so I can modify the JFrame contents. 当从其他类调用此线程时,我需要将其传递给JFrame,以便可以修改JFrame的内容。 How can I do this?
我怎样才能做到这一点? This is for an intro level java course so the teacher gave us most of this code.
这是针对入门级Java课程的,因此老师为我们提供了大部分此类代码。 Below is the code where the Thread gets called:
以下是调用线程的代码:
Button btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cm = new CoinCounterMechanism();
cm.setConsumerFlag();
cm.setProducerFlag();
cm.producer.start();
cm.consumer.start();
}
});
Instead of an anonymous Thread, you create an actual Runnable class. 您可以创建一个实际的Runnable类,而不是一个匿名线程。 You use the constructor to pass your JFrame and other fields.
您可以使用构造函数来传递JFrame和其他字段。
public class Consumer implements Runnable {
private boolean producerFlag;
private JFrame frame;
private Queue<Integer> queue;
public Consumer(JFrame frame, Queue<Integer> queue, boolean producerFlag) {
this.frame = frame;
this.queue = queue;
this.producerFlag = producerFlag;
}
@Override
public void run() {
Integer coin;
while (producerFlag)
try {
coin = queue.take();
System.out.println("Coin received: " + coin);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Your JButton code contains higher level code than the code that actually starts the thread. 您的JButton代码包含比实际启动线程的代码更高级别的代码。 In general, you would start a thread with the Runnable class above this way:
通常,您可以通过上述方式使用Runnable类启动线程:
new Thread(new Consumer(frame, queue, true)).start();
The only thread that should be modifying anything on a JFrame is the event dispatch thread. 事件分配线程是唯一应修改JFrame上任何内容的线程。
In order to have another thread modify a Swing component like a JFrame it needs to submit the change on the event dispatch thread, for example having the worker thread use SwingUtilities#invokeLater : 为了让另一个线程修改像JFrame这样的Swing组件,它需要在事件分发线程上提交更改,例如,让工作线程使用SwingUtilities#invokeLater :
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// modify your JFrame here
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.