简体   繁体   中英

How to twinkle the background color of any JComponent?

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).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM