Jtogglebutton动态设置背景

时间:2016-11-13 08:38:40

标签: java swing jbutton timertask jtogglebutton

我在动态设置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");
    }
});

}

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

}

2 个答案:

答案 0 :(得分:1)

差不多完成了:

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

timer.start();

答案 1 :(得分:-1)

我没有看到使用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();
                        }
                    }
                });