如何在JLabel上放置一个计时器来每秒更新一次

我创建了一个游戏,在我的swing GUI界面中我想放一个计时器。 我现在这样做的方式是有一个当前时间的字段,得到System.currentTimeMillis() ,它在游戏开始时得到它的值。在我的游戏方法中,我把System.currentTimeMillis() – 字段; 并告诉你自游戏开始以来的当前时间。

不过,如何让它每秒更新一次让我们说,所以JLabel会有:timePassed:0s,timePassed:1s等等。 请记住,我在任何时候都不会在游戏中使用线程。

编辑:谢谢大家的善意建议。 我用你的答案组合请给我一些反馈。

我将jlabel称为时间字段。 (否则我无法处理它)。

 time = new JLabel("Time Passed: " + timePassed() + " sec"); panel_4.add(time); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { time.setText("Time Passed: " + timePassed() + " sec"); } }; Timer timer = new Timer(1000, actionListener); timer.start(); 

看看swing计时器课程 。 它允许非常容易地设置重复任务。

这就是我将JLabel设置为随时间和日期更新的方式。

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

然后将其添加到主类中,并使用计时器更新jlabel1 / 2/3。

 new Thread(new Runnable { public void run() { long start = System.currentTimeMillis(); while (true) { long time = System.currentTimeMillis() - start; int seconds = time / 1000; SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText("Time Passed: " + seconds); } }); try { Thread.sleep(100); } catch(Exception e) {} } } }).start(); 

在构造函数中使用此函数

ActionListener taskPerformer = new ActionListener(){

  @Override public void actionPerformed(ActionEvent evt) { jMenu11.setText(CurrentTime()); } }; Timer t = new Timer(1000, taskPerformer); t.start(); 

这写出构造函数

public String CurrentTime(){

  Calendar cal = new GregorianCalendar(); int second = cal.get(Calendar.SECOND); int min = cal.get(Calendar.MINUTE); int hour = cal.get(Calendar.HOUR); String s=(checkTime(hour)+":"+checkTime(min)+":"+checkTime(second)); jMenu11.setText(s); return s; } public String checkTime(int t){ String time1; if (t < 10){ time1 = ("0"+t); } else{ time1 = (""+t); } return time1; 

}