CORRIT_
CORRIT_

Reputation: 55

Update time in JLabel?

So I would like to update the Time in my program. For that I used a JLabel. So when I put the text.setText("Example"); The JLabel doesnt update? Any Ideas why? (I just included every important part of the code, I dont get any Syntax error)

    public JLabel timeNow;
    public static Date dt = new Date(); // current time
    public static int month = dt.getMonth(); // gets the current month
    public static int hours = dt.getHours(); // gets hour of day
    public static int minute = dt.getMinutes();
    public static int second = dt.getSeconds();

public static void main(String[] args) {
        GUI g = new GUI(); //GUI is the name of the class
    g.Update();
    }

public void Update() {
        while(1 == 1) {
            hours = dt.getHours();
            minute = dt.getMinutes();
            second = dt.getSeconds();
            String timeText = "Aktuelle Zeit: " + hours + ":" + minute + ":" + second;
            timeNow.setText(timeText);
        }
    }

Upvotes: 1

Views: 1037

Answers (2)

Colin
Colin

Reputation: 3524

Updates to the UI should happen on the EventDispatch thread, to achieve this replace timeNow.setText(timeText) with

SwingUtilities.invokeLater(
    new Runnable()
    {
        public void run()
        {
            timeNow.setText(timeText);
        }
    });

As @BeUndead said in the comments, you're not updating the dt object, so doing this will still only write the original date time, you need to get a new date time as well.

A better way would be to use a Timer object which creates an event within which you update the UI.

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

To update GUI in Swing you should do it within EventDispatch thread:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GUI extends JFrame implements ActionListener {

    private final JLabel timeLabel = new JLabel();
    private final DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

    public GUI() {
        setLayout(new BorderLayout());
        add(timeLabel, BorderLayout.CENTER);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(300, 100);
        new Timer(500, this).start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new GUI().setVisible(true));
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        timeLabel.setText(df.format(new Date()));
    }
}

Upvotes: 1

Related Questions