在500毫秒内更改JButton颜色 [英] Change JButton color in 500ms

查看:83
本文介绍了在500毫秒内更改JButton颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是让Button在按下按钮时每500毫秒将其颜色从红色更改为黑色.每次按一下按钮,即可启动和停止.

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!

推荐答案

最好的方法是使用类javax.swing.Timer.这是我的解决方案,如何改进您的代码.

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

这篇关于在500毫秒内更改JButton颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆