0

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

我不知道如何从其他不相关的类中调用这些组件。当我试图获得例如height组件时,一切都像魅力一样,但是当我尝试set任何事情时,什么都没有发生!

这是我的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);
        }
    }
}
4

3 回答 3

1

为了在 Event Dispatch Thread 之外修改 GUI 的外观,您有几个选项。您可以使用SwingUtilities.invokeLater并传递 aRunnable来完成您的任务,或者使用SwingWorker.

于 2013-10-27T21:03:44.677 回答
0

确保您实际显示您的框架。

这是来自基本 Swing 教程的示例代码:

JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);

//Display the window.
frame.pack();
frame.setVisible(true);

编辑:请注意,您缺少最后两行。(如果您已经可以看到一个框架,我猜您实际上是在看一个不同的框架,而不是在您的代码中生成的那个。)

于 2013-10-27T21:09:51.380 回答
0

经过一番痛苦,我找到了答案!

这是我所做的:我在构造函数中添加了JFrame参数Producer,当我在其中构造生产者时,startButtonMouseClicked我将this作为JFrame类型参数传递。这个公升技巧让我可以按照我想要的方式访问所有内容。

于 2013-10-27T21:40:18.903 回答