Using java timer in JFrame

17,416

Run this example. I use a Swing Timer and set the delay to 4 seconds. When the button is pressed, it fires an action to change the color and start the timer. When the 4 seconds is up, the color changes back

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
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.SwingUtilities;
import javax.swing.Timer;

public class GreenToRed extends JPanel {
    private Color color = Color.RED;                 // global color object
    static JButton button = new JButton("Change");
    private Timer timer = null;

    public GreenToRed(){

        timer = new Timer(4000, new ActionListener(){      // Timer 4 seconds
            public void actionPerformed(ActionEvent e) {
                color = Color.RED;                         // after 4 seconds change back to red
                repaint();
            }
        });


        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                color = Color.GREEN;        // change to green
                repaint();                  // repaint
                timer.start();              // start timer
            }
        });
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.add(new GreenToRed(), BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        g.fillOval(getWidth() / 2 - 50, getHeight() / 2 - 50, 100, 100);
    }

    public Dimension getPreferredSize() {
        return new Dimension(300, 300);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

enter image description here

Share:
17,416
Ahmet Emin Pehlivan
Author by

Ahmet Emin Pehlivan

Updated on June 04, 2022

Comments

  • Ahmet Emin Pehlivan
    Ahmet Emin Pehlivan almost 2 years

    when handset button pressed I want to green button color change red.After a certain time,again I want to green button.I dont use timer class.Please help me.

    For example my code

            if (e.getSource() == handsetbutton) {
    
                                  text1.setBackground(Color.RED);
    
                              // What l have to add here?
    
    
    
            }
    
  • Paul Samsotha
    Paul Samsotha over 10 years
    add timer.stop() after the repaint() in the timer