Search code examples
javaswinguser-interfacetimerjframe

How to get blinking colon on my digital clock gui?


I coded a digital clock using JFrame. I have the clock working with the seconds ticking but I can't get the colons to blink.

I tried blinking filled rectangle to cover the colon with background and to remove the rectangle every second but it didnt work

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

Solution

  • Change code of the

    actionPerformed(ActionEvent ae)

    method as follows.

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

    then it will blink the : colon.