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.NOTE: Not all Components / JComponents actually change the background through calls to setBackground