如何在我的数字时钟 gui 上闪烁冒号



我用JFrame编写了一个数字时钟。我让时钟在秒滴答作响的情况下工作,但我无法让冒号闪烁。

我尝试闪烁填充矩形以用背景覆盖冒号并每秒删除矩形,但它不起作用

import java.awt.Font;
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) {
    Watch time = new Watch("time");
    JFrame f = new JFrame("Digital Clock");
    f.setSize(300,150);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLayout(new GridLayout(3, 1));
    f.add(time);
    f.setVisible(true);
  }
}
class Watch extends JLabel implements ActionListener {
  String type;
  SimpleDateFormat sdf;
  public Watch(String type) {
    this.type = type;

    switch (type) {
      case "time" : sdf = new SimpleDateFormat("hh:mm:ss a");
                    setFont(new Font("sans-serif", Font.PLAIN, 40));
                    setHorizontalAlignment(SwingConstants.CENTER);
                    break;
      default     : sdf = new SimpleDateFormat();
                    break;
    }
    Timer t = new Timer(1000, this);
    t.start();
  }
  public void actionPerformed(ActionEvent ae) {
    Date date = new Date();
    setText(sdf.format(date));
  }
}

更改代码

actionPerformed(actionEvent ae(

方法如下。

int count = 0;
public void actionPerformed(ActionEvent ae) {
    Date date = new Date();
    String dateText = sdf.format(date);
    if (count % 2 == 0) {
        dateText = dateText.replace(":", " ");
        setText(dateText);
    }
    setText(dateText);
    count++;
}

然后它将闪烁 : 冒号。

最新更新