My task is to make a Button change his color every 500ms from red to black, when pressing it. This should start and stop by every push on the Button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Button extends JButton{
public Button() {
setBackground(Color.red);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
change ^= true;
while(change) {
setBackground(Color.black);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {}
setBackground(Color.red);
}
}
});
}
boolean change = false;
}
This Code doesnt work for me, I hope someone is able to help!
The best idea here is to use the class
javax.swing.Timer
. Here is my solution, how to improve your code to do it.