import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FrameTest extends JFrame {
public FrameTest() {
super("Swing 例子");
this.setSize(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.add(new CounterJButton());
this.add(new CounterJButton());
this.add(new CounterJButton());
this.setVisible(true);
}
static class CounterJButton extends JButton implements Runnable,
ActionListener {
private boolean started = false;
private int count = 0;
public CounterJButton() {
super("按我开始计数");
this.addActionListener(this);
}
public void run() {
while (started) {
this.setText("按我暂停 " + String.valueOf(count++));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
public void actionPerformed(ActionEvent e) {
if (started) {
this.started = false;
this.setText("按我恢复计数 " + count);
} else {
this.started = true;
new Thread(this).start();
}
}
}
public static void main(String[] args) {
new FrameTest();
}
}