Reputation: 502
My goal is creating a function that waits half second, set the jbutton's background to red for one second, and after this second the jbutton will return to normal. Cant make this work.. This is my Function
private void paint(final int num){
Timer timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (num == 1){
btn.setBackground(Color.black);
}
}
});
timer.start();
}
Upvotes: 1
Views: 230
Reputation: 3819
Well, this would do it (note, you would probably want to put the code from the first sleep onwards into a timer or it's own thread in a real application to avoid blocking the thread running the code):
public static void main(String[] args) throws Exception {
final JFrame jf = new JFrame();
final JButton jButton = new JButton("Hello");
final Color originalBackground = jButton.getBackground();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jf.getContentPane().add(jButton);
jf.pack();
jf.setVisible(true);
}
});
Thread.sleep(500);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jButton.setBackground(Color.RED);
}
});
Thread.sleep(1000);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jButton.setBackground(originalBackground);
}
});
Upvotes: 0
Reputation: 1695
Start a 500ms timer that will do two things when it goes off:
- change the color to red
- start a 1s timer that will change the color to normal, when it goes off
Upvotes: 1