更新JLabel中的时间?

huangapple go评论81阅读模式
英文:

Update time in JLabel?

问题

以下是翻译好的内容:

public JLabel timeNow;
public static Date dt = new Date(); // 当前时间
public static int month = dt.getMonth(); // 获取当前月份
public static int hours = dt.getHours(); // 获取小时
public static int minute = dt.getMinutes();
public static int second = dt.getSeconds();

public static void main(String[] args) {
    GUI g = new GUI(); // GUI是类的名称
    g.Update();
}

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

注意:这段代码存在一个问题,即while (1 == 1)会导致无限循环,可能会导致程序无响应。建议使用合适的循环条件来避免这个问题。

英文:

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);
		}
	}

答案1

得分: 1

UI的更新应该在EventDispatch线程上进行,要实现这一点,请使用以下代码替换timeNow.setText(timeText)

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

正如@BeUndead在评论中所说,您没有更新dt对象,因此这样做仍然只会写入原始日期时间,您还需要获取新的日期时间。

一个更好的方法是使用Timer对象,在其中创建一个事件,您可以在其中更新UI。

英文:

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.

答案2

得分: 1

更新Swing中的GUI应该在“EventDispatch”线程中进行:

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()));
    }
}
英文:

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()));
    }
}

huangapple
  • 本文由 发表于 2020年9月21日 23:03:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63994989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定