如何在我的数字时钟GUI上获得冒号冒号?

时间:2019-07-10 04:04:20

标签: java swing user-interface timer jframe

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

1 个答案:

答案 0 :(得分:0)

更改

的代码
  

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

然后它将闪烁:冒号。