Runnable q = new ColourPanelRx();
Thread s = new Thread(q);
s.start();
This is okay to do but it creates and starts up a new instance, not this enclosing class, but another that doesn't do anything because it isn't shown in a gui. To do this with the enclosing class you can build some state (member variables: thread and animate) and some methods to make things happen (start and stop).
To check this idea out, ie, "a new instance not getting shown", you could see what happens with this:
Runnable q = new ColourPanelRx();
Thread s = new Thread(q);
s.start();
// JPanel default size is 10,10.
((JComponent)q).setPreferredSize(new Dimension(100,100));
JOptionPane.showMessageDialog(null, q, "separate instance", -1);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColourPanelRx extends JPanel implements Runnable {
Thread thread;
boolean animate = false;
public void run() {
try {
for (int i=0;i<100000;i++) {
randomNumber = Math.random();
if ((randomNumber >= 0) && (randomNumber < 0.25))
setBackground(Color.RED);
if ((randomNumber >= 0.25) && (randomNumber < 0.5))
setBackground(Color.BLUE);
if ((randomNumber >= 0.5) && (randomNumber < 0.75))
setBackground(Color.MAGENTA);
if ((randomNumber >= 0.75) && (randomNumber <= 1))
setBackground(Color.ORANGE);
repaint();
// setVisible(true);
Thread.sleep(1000);
if(!animate) break;
}
} catch (InterruptedException e) {
stop();
}
}
private void start() {
if(!animate) {
animate = true;
thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
}
private void stop() {
animate = false;
if(thread != null)
thread.interrupt();
thread = null;
}
public ColourPanelRx() {
setLayout(new BorderLayout());
colourButton = new JButton("Change Background");
add(colourButton, BorderLayout.SOUTH);
colourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.printf("this = %s%nthis.enclosingClass = %s%n",
this.getClass().getName(),
this.getClass().getEnclosingClass().getName());
// Runnable q = new ColourPanelRx();
// Thread s = new Thread(q);
// s.start();
start();
}
});
}
private JButton colourButton;
private double randomNumber;
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new ColourPanelRx());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}