我有一个动态设置Jtogglebutton的背景颜色的问题。我想让Jtoggle按钮像指示灯一样闪烁,并在特定时间开启和关闭,如500毫秒。我试图重写paint和paintComponent方法。但也不能成功。我卡住了。这是我的代码,感谢您的帮助。Jtogglebutton动态设置背景
领导类:
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);
}
}
1)为了更好地帮助更快,发布[MCVE]或[短的,独立的,正确的示例](http://www.sscce.org/)。 2)请参阅[检测/修复代码块的悬挂紧密支架](http://meta.stackexchange.com/q/251795/155831),以解决问题,我不再担心修复问题。 –
我不确定我是否理解,您希望颜色每隔500毫秒切换一次,或者您希望按钮的状态切换,然后触发颜色切换? –
我想每隔500ms切换一次按钮的颜色。国家并不重要。 –