Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update JFrame Label within a Thread? - Java

I have tried a lot, but can't seem to get it to work.

I was told to use EDT with the following example.

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //  Modify the GUI here
        }
});

I have read on this topic a lot and still don't understand. I get what a thread is, but the .invokeLater still makes no sense to me. Honestly if you can explain in detail this it would be a big help!

Goal of Program: To get the randomly generated key that is constantly created every second to update itself afterward in the GUI.

like image 359
Zeveso Avatar asked Nov 22 '10 21:11

Zeveso


People also ask

How do you change a Jlabel text?

To update the text in a label you use label. setText("New text") .

What is class in GUI?

The java. awt package contains the core AWT graphics classes: GUI Component classes, such as Button , TextField , and Label . GUI Container classes, such as Frame and Panel . Layout managers, such as FlowLayout , BorderLayout and GridLayout .


1 Answers

So there is an EDT (Event Dispatch Thread). All actions that appear on your screen are executed by the EDT. There is only one EDT per Swing application.

You are in some arbitrary thread and you want to update the GUI through that thread? Well like I said there is only one EDT for each swing application, so you have to tell that EDT to display the label (or whatever context you want).

The idea here, is you push this Runnable onto a queue that the EDT pulls from. Eventually, your runnable will be processed by the EDT when all other actions before it are completed.

like image 88
John Vint Avatar answered Oct 12 '22 11:10

John Vint