有人能解释一下为什么我的启动/停止按钮不工作吗?这不是一个完全实现的StopWatch,但我被困在这里了。如有任何帮助,我们不胜感激!这是我第一次在论坛上发帖,如果我的帖子中有任何问题,请告诉我。这是我的代码:
public class StopWatch {
private static boolean tiktok;
public static void setGo(boolean go) {
tiktok = go;
}
public static void main(String[] args) {
int counter = 0;
StopWatch stop = new StopWatch();
ClockFrame window = new ClockFrame("StopWatch");
JLabel lb = window.init();
while (true) {
lb.setText(Integer.toString(counter++));
if (counter == 61) {
counter = 0;
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class ClockFrame extends JFrame {
JLabel hour, minus, sec;
public ClockFrame(String title) {
super(title);
}
JLabel init() {
JFrame frame = new JFrame("Stop Watch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel time = new JPanel();
hour = new JLabel("0");
minus = new JLabel("0");
sec = new JLabel("0");
time.add(hour);
time.add(minus);
time.add(sec);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
JButton start = new JButton("Start");
start.addActionListener(new startstopActionListener(true));
JButton stop = new JButton("Stop");
stop.addActionListener(new startstopActionListener(false));
JButton reset = new JButton("Reset");
pane.add(start);
pane.add(stop);
pane.add(reset);
Container window = frame.getContentPane();
window.setLayout(new GridLayout(2, 1));
window.add(pane);
window.add(time);
frame.setSize(500, 200);
frame.setVisible(true);
return sec;
}
}
class startstopActionListener implements ActionListener {
private boolean b;
public startstopActionListener(boolean b) {
this.b = b;
}
@Override
public void actionPerformed(ActionEvent e) {
StopWatch.setGo(b);
}
}发布于 2012-07-16 03:38:02
你不尊重Swing的线程策略:
只能在事件分派thread
阅读Swing tutorial about concurrency。
发布于 2012-07-16 04:27:17
如果你想在Swing中做秒表,你最好看看javax.swing.Timer类。它使得定期更新Swing组件(在您的例子中是JLabel)变得非常容易。使用Timer可避免Thread.sleep调用,因为事件调度线程会阻塞UI,因此不应在事件调度线程上调用该调用。
JB Nizet已经提供了到Swing concurrency tutorial的链接。我建议你也看看这个站点的'Swing info page'的Swing并发部分中提供的链接,以及一个相关问题的my answer。
https://stackoverflow.com/questions/11494902
复制相似问题