gpt4 book ai didi

java - 更改另一个类的 UI 值

转载 作者:行者123 更新时间:2023-12-01 13:56:01 24 4
gpt4 key购买 nike

我正在 Java 中实现消费者-生产者问题,我需要为此添加家伙。我的问题是从 CustomerProducer 类更改 UI 组件。

我不知道如何从其他不相关的类中调用这些组件。当我尝试获取例如组件的高度时,一切都像魅力一样工作,但是当我尝试设置任何东西时,什么也没有发生!

这是我的 Producer 类代码,进行了一些尝试:

public class Producer extends Thread {
// Variable which holds shared queue
private BlockingQueue<String> queue;
// Amount products created by producer
private int steps;
// Object with normaln distribution
private NormalDistribution distribution;

// Accessors to the frame
private PCPMainFrame frame;
private JSlider queueSlider;
private JProgressBar queueProgressBar;

// Constructor with 4 arguments
// q - is our queue shared between customer and producer
// steps - amount of products
// mean - parameter rquired for normal distribution
// standardDeviation - ditto
public Producer(BlockingQueue<String> q, int steps, double mean, double standardDeviation){
this.queue=q;
this.steps = steps;
this.distribution = new NormalDistribution(mean, standardDeviation);
this.frame = new PCPMainFrame();
this.queueSlider = frame.getQueueSlider();
this.queueProgressBar = new JProgressBar();
}

@Override
public void run() {
// Generating products and filling queue with them
for(int i = 0; i < steps; i++){
try {
long sleepTime = Math.abs((long)distribution.sample()*100);
Thread.sleep(sleepTime);
// Saving element in queue
queue.put(String.valueOf(i));
// This is a log for developer needs, feel free to uncomment
System.out.println("Produced: " + i);
queueSlider.setValue(steps);
frame.setQueueProgressBar(queueProgressBar);
} catch (InterruptedException e) {
System.out.println("Producer exception: " + e);
}
}
// Ading exit message at the end of the queue
String exit = new String("exit");
try {
queue.put(exit);
} catch (InterruptedException e) {
System.out.println("Queue exception: " + e);
}
}
}

最佳答案

为了修改事件调度线程之外的 GUI 外观,您有几个选择。您可以使用 SwingUtilities.invokeLater 并传递一个 Runnable 来执行您的任务,或者使用 SwingWorker

关于java - 更改另一个类的 UI 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com