Java Graphics How to - Make a string flash








Question

We would like to know how to make a string flash.

Answer

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from  w  w  w.  j  ava2s. c om
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(new BlinkPane());
    frame.setSize(200, 200);
    frame.setVisible(true);
  }
}

class BlinkPane extends JLabel {
  JLabel label;
  boolean on = true;

  public BlinkPane() {
    label = new JLabel("Hello");
    setLayout(new GridBagLayout());

    add(label);
    Timer timer = new Timer(1000, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent ae) {
        on = !on;
        repaint();
      }
    });
    timer.setRepeats(true);
    timer.setCoalesce(true);
    timer.start();
  }

  @Override
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g.create();
    if (!on) {
      g2d.setComposite(AlphaComposite.SrcOver.derive(0f));
    } else {
      g2d.setComposite(AlphaComposite.SrcOver.derive(1f));
    }
    super.paint(g2d);
    g2d.dispose();
  }

}