简体   繁体   中英

pass JFrame to a thread

I have a class that creates a JFrame. When the start button is clicked, it calls my CoinCounterMechanism class. 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. How can I do this? This is for an intro level java course so the teacher gave us most of this code. 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. You use the constructor to pass your JFrame and other fields.

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. In general, you would start a thread with the Runnable class above this way:

new Thread(new Consumer(frame, queue, true)).start();

The only thread that should be modifying anything on a JFrame is the event dispatch thread.

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 :

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        // modify your JFrame here
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM