Prevent JButton repaint() after click

后端 未结 3 1134
情歌与酒
情歌与酒 2021-01-27 08:38

I have a button. I want to change the background after I click on it. My problem here is the button auto call paintComponent(). How can prevent this? I expect after

3条回答
  •  灰色年华
    2021-01-27 09:24

    If you want to change the background for a short while you can do it with 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.JPanel;
    import javax.swing.Timer;
    
    public class ButtonDemo extends JButton implements ActionListener{
    
        private static final int DELAY = 600; //milliseconds
        private final Timer timer;
    
        public ButtonDemo() {
            this.setText("BUTTON TEXT");
            this.addActionListener(this);
            Color defaultCloor = getBackground();
            timer = new Timer(DELAY, e-> setBackground(defaultCloor));
            timer.setRepeats(false);
        }
    
        public static void main(String[] args){
            JFrame frame = new JFrame();
            JPanel contentPane = new JPanel();
            frame.setContentPane(contentPane);
            contentPane.add(new ButtonDemo());
            frame.setSize(300, 200);
            frame.setVisible(true);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            timer.stop();
            this.setBackground(Color.RED);
            timer.start();
        }
    }
    

提交回复
热议问题