f.mike f.mike - 27 days ago 6
Java Question

Jtogglebutton setting background dynamically

i have a problem with setting background color of Jtogglebutton dynamically. I want Jtogglebutton blink like a led, on and off at a decised time, like 500ms. I tried to override paint and paintComponent method too. But couldn't succeed either. I'm stuck. Here is my code thanks for help.

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


}

M B M B
Answer

I don't see the point in using the Timer class but just a simple thread should work

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