Change JButton color in 500ms

只谈情不闲聊 提交于 2019-12-02 13:26:48

The best idea here is to use the class javax.swing.Timer. Here is my solution, how to improve your code to do it.

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.WindowConstants;

public class Button extends JButton {
    public Button() {
        setBackground(Color.RED);
        setForeground(Color.WHITE);
        addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                change ^= true;

                if (change) {
                    timer.restart();
                } else {
                    timer.stop();
                }
            }
        });
    }

    private boolean change = false;

    private Timer timer = new Timer(500, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (Color.BLACK == getBackground()) {
                setBackground(Color.RED);
            } else {
                setBackground(Color.BLACK);
            }
        }
    });

    public static void main(String[] args) {
        Button b = new Button();
        b.setText("Press me");
        JFrame frm = new JFrame("Test button");
        frm.add(b);
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!