package thread;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
/**
* ButtonTestRunnable.
* <p/>
* User: rro
* Date: 12.07.2005
* Time: 21:53:03
*
* @author Romsl
* @version $Id$
*/
public class ButtonTestRunnable extends JFrame implements Runnable {
private JButton start = new JButton("Starte den Thread");
private JButton stop = new JButton("Stoppe den Thread");
private volatile Thread thread = null;
public ButtonTestRunnable() {
this.setTitle("Button Test");
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(start, BorderLayout.WEST);
this.getContentPane().add(stop, BorderLayout.EAST);
/*
* Wenn du hier den ActionListener implementierst anstatt
* den MouseAdapter so wie du es zu Anfang hattest dann
* funktioniert das ganze mit Tastatur, et cetera.
*/
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonTestRunnable.this.thread = new Thread(ButtonTestRunnable.this);
ButtonTestRunnable.this.thread.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonTestRunnable.this.stop();
}
});
this.pack();
this.setVisible(true);
}
/**
* Diese Methode wurde eingeführt um den unsicheren stop
* per Thread.stop() zu umgehen.
* Desweiteren gehört in der run() noch das
* Thread thisThread = Thread.currentThread(); und
* die Abfrage thisThread == thread; dazu
*/
public void stop() {
thread = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
for (int i = 0; thisThread == thread; i++) {
if (this.start != null) {
int j = i % 4;
switch (j) {
case 0:
start.setBackground(Color.BLUE);
break;
case 1:
start.setBackground(Color.RED);
break;
case 2:
start.setBackground(Color.YELLOW);
break;
case 3:
start.setBackground(Color.PINK);
break;
default: start.setBackground(Color.LIGHT_GRAY);
}
}
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
thread.interrupt();
}
}
}
public static void main(String[] args) {
new ButtonTestRunnable();
}
}