我有一个问题,设置背景颜色的Jtogglebutton动态。我要Jtogglebutton像led一样眨眼,断断续续,就像500 at一样。我也试图覆盖油漆和paintComponent方法。但也没能成功。我卡住了。这是我的代码,谢谢你的帮助。
Led班:
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");
}
});}
MainFrame类:
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);
}}
发布于 2016-11-13 09:13:49
我不认为使用Timer类有什么意义,但只要一个简单的线程就可以工作
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();
}
}
});发布于 2016-11-13 09:14:08
这项工作几乎完成:
Timer timer=new Timer(BLINK_FREQUENCY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setBackgroundColor(getBackgroundColor()==okColor ? noOkColor:okColor);
}
});
timer.start();https://stackoverflow.com/questions/40572016
复制相似问题