Start New Discussion within our Software Development Community

I am trying to change the background color of the JPanel every 3 seconds (3000 ms) when I click START button till I press STOP button.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

class TimerBackground implements ActionListener
	JFrame frame; 	JPanel panel;
	JButton btnStart; 	JButton btnRed;
	JButton btnGreen; 	JButton btnBlue;
	JButton btnStop; 	Timer t;  
	Random num = new Random();  
	int r, g, b;
		r = g = b = 0;
		frame = new JFrame("Timer Background");
		panel = new JPanel();
		btnStart = new JButton("START");
		btnRed = new JButton("Red");
		btnGreen = new JButton("Green");
		btnBlue = new JButton("Blue");
		btnStop = new JButton("STOP");
		t = new Timer(3000, this);


	public void actionPerformed(ActionEvent evnt)
		if(evnt.getSource() == btnRed)
			panel.setBackground(new Color(255,0,0));
		else if(evnt.getSource() == btnGreen)
			panel.setBackground(new Color(0,255,0));
		else if(evnt.getSource() == btnBlue)
			panel.setBackground(new Color(0,0,255));
		else if(evnt.getSource() == btnStart)
			//Are The Lines Below Correct or else What Should I Write Here??
			r = num.nextInt(255);
			g = num.nextInt(255);
			b = num.nextInt(255);
			panel.setBackground(new Color(r, g, b));
		else if(evnt.getSource() == btnStop)

	public static void main(String[] args)
		TimerBackground timerB = new TimerBackground();

The above code works only once on click of START button. I don't understand how to make it run every 3 seconds.

javax.swing.Timer is what you need - documentation & samples in the usual places.

Define a timer task (a "run()" method) that you want to run repeatedly. On click of the start button start a Timer that will run that task every 3000 msec. On click of the stop button stop the timer.

Hey! Was that deliberate? Normal phrase is "heart of gold", but you wrote "hard" as in tough. difficult etc. Neat pun!
I still stand by what I said.

thank you, my fast hands and still problems wrote English words correctly, nor ...

but my reaction == this forum is long times one man show throught EU working hours, with my respect man

also implement a loop if that operation is to keep on being repeated

No no no.

The javax.swing.Timer handles the repeating. If you tell a newbie to use a loop in this context you will get a loop with a sleep in it that blocks the EDT and leads inevitably to the post that goes "why isn't by background updating?".

So, no, no loop. Just a swing Timer.

Hey I used TimerTask one as suggested by James Cherrill... Thanks.. I had to dig deep, but I found out..

This question has already been answered. Start a new discussion instead.