How to twinkle the background color of any JComponent?

153 views Asked by At

I'm trying to twinkle the background color of a JButton but only the 'sleep' it's working.

My code:

@Override
public void actionPerformed(ActionEvent e){

  if(!empty){
  }else{
  myButton.setBackground(Color.RED);
  try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e2){}
  myButton.setBackground(Color.LIGHT_GRAY);
  try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {}
  myButton.setBackground(Color.RED);
  try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {}
  myButton.setBackground(Color.LIGHT_GRAY);
  }
  }
}

EDIT: Can't post the whole code, so many lines. The button is inside a GridBagLayout:

myButton= new Jbutton("Button!");
myButton.setBackground(Color.White);
myButton.setHorizontalAlignment(JTextField.CENTER);;
myButton.setForeground(Color.black);
GridBagConstraints gbc_myButton = new GridBagConstraints();
gbc_myButton.fill = GridBagConstraints.BOTH;
gbc_myButton.gridx = 0;
gbc_myButton.gridy = 1;
gbc_myButton.gridwidth=3;
panel.add(myButton, gbc_myButton);

EDIT 2: I just figure out it's not setting any color at runtime (with or without any delay/sleep).

2

There are 2 answers

5
ControlAltDel On BEST ANSWER

You need to use javax.swing.Timer to do animations like this.

final Button b = ...;
final Color[] colors = ...;
colors[0] = Color.RED;
colors[1] = Color.LIGHT_GREY;
ActionListener al = new ActionListener() {
  int loop = 0;
  public void actionPerformed(ActionEvent ae) {
    loop = (loop + 1) % colors.length;
    b.setBackground(colors[loop]);
  }
}

new Timer(200, al).start();

NOTE: Not all Components / JComponents actually change the background through calls to setBackground

2
weston On

The problem is that when you sleep the UI thread (via TimeUnit...sleep(x)), it won't be able to re-render the changes. I bet the last colour does get rendered.

You need to find an alternative way of triggering the color changes, look at timers, particularly swing timer.