Change JButton color in 500ms

一笑奈何 提交于 2019-12-31 07:42:16

问题


My task is to make a Button change his color every 500ms from red to black, when pressing it. This should start and stop by every push on the Button.

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

This Code doesnt work for me, I hope someone is able to help!


回答1:


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


来源:https://stackoverflow.com/questions/52256784/change-jbutton-color-in-500ms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!