使用 ActionListener 更新时钟 - Java

Update a clock using ActionListener - Java

我想要 Java 中的数字时钟显示时间和日期,并且冒号应该闪烁。但是,我不能让冒号闪烁。这是我的代码:

import java.awt.Font;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.SwingConstants;
import java.util.*;
import java.text.*;

public class DigitalClock {

  public static void main(String[] arguments) {

    ClockLabel dateLable = new ClockLabel("date");
    ClockLabel timeLable = new ClockLabel("time");
    ClockLabel dayLable = new ClockLabel("day");

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame f = new JFrame("Digital Clock");
    f.setSize(300,150);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLayout(new GridLayout(3, 1));

    f.add(dateLable);
    f.add(timeLable);
    f.add(dayLable);

    f.getContentPane().setBackground(Color.black);

    f.setVisible(true);
  }
}

class ClockLabel extends JLabel implements ActionListener {
  String type;
  SimpleDateFormat sdf;
  public ClockLabel(String type) {
    this.type = type;
    setForeground(Color.green);
    Calendar calendar = Calendar.getInstance();
    int seconds = calendar.get(Calendar.SECOND);
    switch (type) {
      case "date" : sdf = new SimpleDateFormat("  MMMM dd yyyy");
                    setFont(new Font("sans-serif", Font.PLAIN, 12));
                    setHorizontalAlignment(SwingConstants.LEFT);
                    break;
      case "time" : if(seconds % 2 != 0) sdf = new SimpleDateFormat("hh:mm:ss a");
                    else sdf = new SimpleDateFormat("hh mm ss a");
                    setFont(new Font("sans-serif", Font.PLAIN, 40));
                    setHorizontalAlignment(SwingConstants.CENTER);
                    break;
      case "day"  : sdf = new SimpleDateFormat("EEEE  ");
                    setFont(new Font("sans-serif", Font.PLAIN, 16));
                    setHorizontalAlignment(SwingConstants.RIGHT);
                    break;
      default     : sdf = new SimpleDateFormat();
                    break;
    }
    Timer t = new Timer(1000, this);
    t.start();
  }

  public void actionPerformed(ActionEvent ae) {
      Date d = new Date();
    setText(sdf.format(d));
  }
}

如您所见,我有以下几行:

case "time" : if(seconds % 2 != 0) sdf = new SimpleDateFormat("hh:mm:ss a");
              else sdf = new SimpleDateFormat("hh mm ss a");

这样,当秒数为奇数时冒号可见,否则冒号不可见。

问题是,如果我启动程序并且当时第二个是奇数,那么冒号总是可见的。我不明白为什么,因为第二次更改(时间更新),但冒号没有。

我认为你需要填写这张支票

if(seconds % 2 != 0) 
  sdf = new SimpleDateFormat("hh:mm:ss a");
else 
  sdf = new SimpleDateFormat("hh mm ss a");

actionPerformed 方法中。这就是您可以每秒切换 : 的方式。

如果您 运行 您的项目处于调试模式,您将了解 switch-case 语句 运行 仅一次(在启动时)。根据上面的实现,这是正常的,因为逻辑被放置在仅调用树次的构造函数中。

简而言之,您需要彻底更改此实现。