Jtogglebutton动态设置背景

Jtogglebutton setting background dynamically

我在动态设置 Jtogglebutton 的背景颜色时遇到问题。我希望 Jtogglebutton 像 LED 一样闪烁,在确定的时间打开和关闭,比如 500 毫秒。我也尝试重写 paint 和 paintComponent 方法。但也未能成功。我卡住了。这是我的代码,感谢您的帮助。

领导 class:

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");
    }
});

}

主机Class:

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);
}

}

我看不出使用计时器有什么意义class,但一个简单的线程应该可以工作

public Led() {
    this.setPreferredSize(new Dimension(50, 50));
    thread.start();
}

Thread  thread  = new Thread(() -> {
                    while (true) {
                        if (getBackground().equals(notOkColor)) {
                            setBackground(okColor);
                        } else {
                            setBackground(notOkColor);
                        }
                        try {
                            Thread.sleep(BLINK_FREQUENCY);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });

快完成了:

    Timer timer=new Timer(BLINK_FREQUENCY, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
          setBackgroundColor(getBackgroundColor()==okColor ? noOkColor:okColor);
    }
    });

timer.start();