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;
TimerBackground()
{
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);
btnStart.addActionListener(this);
btnStop.addActionListener(this);
btnRed.addActionListener(this);
btnBlue.addActionListener(this);
btnGreen.addActionListener(this);
t.addActionListener(this);
frame.setSize(800,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setContentPane(panel);
panel.add(btnStart);
panel.add(btnStop);
panel.add(btnRed);
panel.add(btnGreen);
t.start();
}
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)
{
t.stop();
}
}
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.