Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable blinking of JLabel 3 times and then remain invisible/disappear

I intend on writing java code which controls a JLabel to blink three times and then after the third blink enable the text within it to remain transparent/"disappear."

As indicated from the code below, I've been able to write a JLabel which continuously blinks but would like to create one that blinks only three times and then enable the text within it to remain transparent.

public class BlinkLabel extends JLabel {

      private static final long serialVersionUID = 1L;

      private static final int BLINKING_RATE = 1000; // in ms

      private boolean blinkingOn = true;

      public Timer timer;

      public BlinkLabel(String text) {
        super(text);            
        timer = new Timer( BLINKING_RATE , new TimerListenerTwo());
        timer.setInitialDelay(0);
        timer.start();

      }

      public void setBlinking(boolean flag) {
        this.blinkingOn = flag;
      }

      public boolean getBlinking(boolean flag) {
        return this.blinkingOn;
      }

      public class TimerListenerTwo implements ActionListener{
            int counter = 1;

            public TimerListenerTwo() {

            }

            public void actionPerformed(ActionEvent evt){
                if(counter == 3){//3 = YOUR MAX
                    timer.stop();
                }
                counter++;
            }
       }
}

I call the above function as follows:

BlinkLabel label = new BlinkLabel("");
label.setText("Blink blink");

How can I edit my above code to enable the JLabel to blink three time and have the text disappear.

Any ideas/suggestions are greatly appreciated.

like image 537
TokTok123 Avatar asked Sep 01 '25 21:09

TokTok123


1 Answers

Its very simple, create a sub class below in your JFrame or JDialog.

class LbBlink implements ActionListener {  
        private javax.swing.JLabel label;
        private java.awt.Color cor1 = java.awt.Color.red;
        private java.awt.Color cor2 = java.awt.Color.gray;
        private int count;

        public LbBlink(javax.swing.JLabel label){
            this.label = label;
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            if(count % 2 == 0)
                label.setForeground(cor1);
            else
                label.setForeground(cor2);
            count++;
        }  
    }

Declare a variable in your class.

private Timer timerLB;

After, in your class construct set the variable.

timerLB = new Timer(1000, new "Your Class".LbBlink("Your jLabel"));

Finally, in your application, for start blink

timerLB.start();

And for stop:

timerLB.stop();
like image 126
Fernando Rossato Avatar answered Sep 03 '25 10:09

Fernando Rossato