Change JButton color in 500ms

后端 未结 1 1301
我在风中等你
我在风中等你 2021-01-29 13:43

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         


        
1条回答
  •  日久生厌
    2021-01-29 14:06

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

    0 讨论(0)
提交回复
热议问题