java - java中如何在不关闭UI的情况下更新时间?

标签 java user-interface time

我想创建一个具有计时/超时功能的系统。

在将该功能添加到我的系统之前,我尝试了此代码:

import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Time extends JFrame implements ActionListener {

     Date now = new Date();
     private JLabel time;
     private JButton getTime;
     private SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss");

public Time()
{

  setLayout(null);
  setSize(500,300);


  JLabel time = new JLabel("00:00:00");
  time.setSize(100,100);
  time.setLocation(40,40);

  JButton getTime = new JButton("GET TIME");
  getTime.addActionListener(this);
  getTime.setSize(90,30);
  getTime.setLocation(90,70);

  Container pane = getContentPane();

  pane.add(time);
  pane.add(getTime);

  setVisible(true);

}

public void actionPerformed(ActionEvent e)
{
    if (e.getActionCommand() == "GET TIME")
    {
        JOptionPane.showMessageDialog(null, "Time "+dateFormatter.format(now),       
"Time.",JOptionPane.INFORMATION_MESSAGE);
}
}

public static void main(String[] args) {
  new Time();
}
}

它获取当前时间,但当我再次单击按钮时它仍然给出相同的时间。仅当我关闭用户界面时它才会改变。

最佳答案

预设答案:

不要使用 == 比较字符串。请改用 equals(...)equalsIgnoreCase(...) 方法。了解 == 检查两个对象是否相同,这不是您感兴趣的。另一方面,这些方法检查两个字符串是否具有相同顺序的相同字符,并且这才是重要的。所以而不是

if (fu == "bar") {
  // do something
}

做,

if ("bar".equals(fu)) {
  // do something
}

或者,

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}
<小时/>

未预设的答案:

换句话说,改变这个:

if (e.getActionCommand() == "GET TIME")

对此:

if ("GET TIME".equals(e.getActionCommand())

或者更好的是,使用字符串常量。

此外,您还需要避免在 Swing GUI 中使用空布局,因为您会发现这是一种很难进行布局的方法。使用布局管理器更简单、更强大。

编辑
您需要从 actionPerformed 方法中获取时间。换句话说,应该在调用 JOptionPane 之前在 actionPerformed 方法中创建 now

public void actionPerformed(ActionEvent e)
{
    if (e.getActionCommand() == "GET TIME")
    {
        now = new Date();
        JOptionPane.showMessageDialog(null, "Time "+dateFormatter.format(now),       

关于java - java中如何在不关闭UI的情况下更新时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771125/

相关文章:

java - 使用 junit 测试 map 时使用通用有界通配符

javascript - 每秒刷新日期的函数最终导致 Chrome 崩溃

ios - PsychoPy 编码器 : define image duration based on frames

c++ - 用于基于语音的命令激活的开源库

java - 如何使用按钮在文本字段中键入内容?

java - GUI Java-如何使用2个用户输入的数字来得到答案

c - 在 C 中将 time_t 设置为下一个晚上 10 点?

java - 在 AppEngine 中解码国际字符

java - 安卓工作室错误 : Failed to Resolve.。 <图书馆名称>

java - 使用参数 null 重载方法调用