【问题标题】:Change JButton color in 500ms在 500 毫秒内更改 JButton 颜色
【发布时间】:2019-02-14 19:53:26
【问题描述】:

我的任务是让按钮每 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;
}

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

【问题讨论】:

    标签: java swing loops colors sleep


    【解决方案1】:

    这里最好的办法是使用类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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 2015-12-12
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多