java - 在 500 毫秒内改变 JButton 颜色

标签 java swing loops colors sleep

我的任务是让按钮在按下时每 500 毫秒改变一次颜色,从红色变为黑色。每次按下按钮时都会开始和停止。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Button extends JButton{
    public Button() {
    setBackground(Color.red);
    addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            change ^= true;

            while(change) {
                setBackground(Color.black);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {}
                setBackground(Color.red);
            }
        }
    });
    }
    boolean change = false;
}

此代码对我不起作用,我希望有人能够提供帮助!

最佳答案

这里最好的想法是使用类javax.swing.Timer。这是我的解决方案,如何改进您的代码来做到这一点。

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

关于java - 在 500 毫秒内改变 JButton 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56470540/

相关文章:

java - 有没有办法从 StringBuilder 解析日期?

java - 当 TreeModel 添加新节点时,为什么我的 JTree 没有更新?

java - 使用 MediaTracker 在 Swing 应用程序中缓存图像

arrays - 尝试使用循环创建具有不同值的字符串

涉及 char 和 String 的 Java 循环问题

jquery - 简化 slider 的 jquery 脚本

java - MigLayout 限制 JList 在 JScrollPane 上的滚动

java - 如何在不使用函数setZOrderOnTop(true)的情况下使SurfaceView的背景透明?

java - 什么会导致 @XmlRootElement 类被解码到 JaxbElement 中?

java - 刷新 JLabel 图标图像