Jtogglebutton の背景色を動的に設定する際に問題があります。Jtogglebutton を LED のように点滅させ、500ms のように決まった時間にオンとオフを切り替えます。paint と paintComponent メソッドもオーバーライドしようとしました。しかし、成功することもできませんでした。私は立ち往生しています。これが私のコードです。助けてくれてありがとう。
導かれたクラス:
public class Led extends JToggleButton {
private Color okColor = Color.GREEN;
private Color notOkColor = Color.RED;
private static int BLINK_FREQUENCY=500;
public Led() {
this.setPreferredSize(new Dimension(50, 50));
timer.start();
}
Timer timer=new Timer(BLINK_FREQUENCY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setBackground(okColor);
System.out.println("ok");
try {
Thread.sleep(BLINK_FREQUENCY);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
setBackground(notOkColor);
System.out.println("notok");
}
});
}
メインフレーム クラス:
public class MainFrame {
private JFrame frame;
private Led led;
private JPanel panel;
public MainFrame() {
initializeComponents();
}
private void initializeComponents() {
frame = new JFrame("Blinking Led");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
{
panel = new JPanel();
led = new Led();
panel.add(led);
frame.add(panel);
}
}
public void setVisible(boolean visible) {
frame.setVisible(visible);
}
}