简体   繁体   中英

Is there a way to update JLabel text real-time and manually?

JLabel (or any other JComponents), when you call the setText() method, its value changed but the look in the UI need to be updated later. (by EDT?)

And if you blocked EDT, the whole frame freezes. So my problem is, I'm happy with the 'freeze' effect prevents any more actions dispatch. However I want my labels and other outputting components keep updating. Therefore I am looking for a method that update the look of a component manually. In java API, I found updateUI() which seems not useful.

If you know any method that can do like

label.setText("thanks!");
label.update(); 

Please tell me. I will be very grateful.

Don't freeze the Swing event thread, period. When you do, it isn't able to perform any of its tasks such as painting and user interaction, and if it doesn't paint, it doesn't update, no matter what you try. Simple as that.

Is there a way to update JLabel text real-time and manually?

No, do it on the EDT.

Step 1) Don't block the event dispatch thread.
Step 2) Update the label as usual, by calling setText.

This is how I would set my JLabel to update with time & date.

    SimpleDateFormat SimpleDay = new SimpleDateFormat("EEEE");
    SimpleDateFormat SimpleDate = new SimpleDateFormat("dd MMMM yyyy");
    SimpleDateFormat SimpleTime = new SimpleDateFormat("H:mm:ss");

    Timer SimpleTimer = new Timer(1000, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            jLabel1.setText(SimpleDay.format(new Date()));
            jLabel2.setText(SimpleDate.format(new Date()));
            jLabel3.setText(SimpleTime.format(new Date()));
        }
    });
    SimpleTimer.start();

This is then added to your main class and the jlabel1/2/3 get updated with the timer.

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