How to make a button blink?

3

I created a simple code for a game similar to Genius, where a random button on a set of 20 buttons starts flashing, but I can not seem to break the color change.

Here is an example, basically I just need the color of the button to change randomly, from 0.3 in 0.3 sec ...

try{
    for (int i = 0; i < 255; i++){ 

        //define a proxima cor aleatoria
        cor1 = (int)(Math.random()*255)+1;

        //deveria gerar o atraso de 0,3s
        Thread.sleep(300);

        jButton1.setBackground(new Color (cor1,00,00));

    }

}catch (InterruptedExcepetion e){}
    
asked by anonymous 09.05.2015 / 12:46

1 answer

3

I would do it as follows:

  • A Java Swing Timer to control the entire process
  • Every 0.3s an event is triggered that you process through an ActionListener
  • In ActionListener you choose the color in a random way and you change the button

Here is a small example of how you can do it:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Example extends JFrame
{
    private JButton button;
    private Timer timer;
    private int delay = 300; // a cada 0,3 segundos
    private static final long serialVersionUID = 1L;
    Random rand = new Random();

    public SimpleTimer()
    {
        super("Teste");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        button = new JButton("O meu botão");
        JPanel contentPane = (JPanel) getContentPane();
        contentPane.add(button, BorderLayout.CENTER);
        contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        pack();

        ActionListener action = new ActionListener()
        {   
            @Override
            public void actionPerformed(ActionEvent event)
            {
                    float r = rand.nextFloat();
                    float g = rand.nextFloat();
                    float b = rand.nextFloat();

                    button.setBackground(new Color(r, g, b));
            }
        };

        timer = new Timer(delay, action);
        timer.setInitialDelay(0);
        timer.start();

        setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new SimpleTimer();
            }
        });
    }
}
    
09.05.2015 / 13:35