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
The best idea here is to use the class javax.swing.Timer
. Here is my solution, how to improve your code to do it.
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class Button extends JButton {
public Button() {
setBackground(Color.RED);
setForeground(Color.WHITE);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
change ^= true;
if (change) {
timer.restart();
} else {
timer.stop();
}
}
});
}
private boolean change = false;
private Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (Color.BLACK == getBackground()) {
setBackground(Color.RED);
} else {
setBackground(Color.BLACK);
}
}
});
public static void main(String[] args) {
Button b = new Button();
b.setText("Press me");
JFrame frm = new JFrame("Test button");
frm.add(b);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}