如何操作按钮来停止和启动时钟,而我希望按下按钮时停止并继续计数并更改其标签。
现在我发现按钮开始计数并在之后更改标签不起作用。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ex1 extends JFrame implements Runnable {
int time = 0;
JLabel lb1 = new JLabel("Hours:");
JLabel lb2 = new JLabel("Minutes:");
JLabel lb3 = new JLabel("Seconds:");
JTextField hrs = new JTextField(10);
JTextField mts = new JTextField(10);
JTextField scd = new JTextField(10);
JPanel Lcontent = new JPanel();
Thread t = new Thread(this);
boolean flag = false;
JButton stp = new JButton("Start");
JFrame fr1 = new JFrame("Swing Window");
Container cp;
int mnts = 0;
int hors = 0;
public Ex1() {
fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr1.setSize(700, 90);
fr1.setResizable(true);
cp = fr1.getContentPane();
cp.setLayout(new FlowLayout());
cp.add(lb1);
cp.add(hrs);
cp.add(lb2);
cp.add(mts);
cp.add(lb3);
cp.add(scd);
cp.add(stp);
stp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (flag == false) {
stp.setText("Stop");
t.start();
}
flag = true;
//stp.setText("Start");
//t.stop();
}
});
fr1.show();
}
public void run() {
while (flag) {
try {
Thread.sleep(1000);
time++;
scd.setText("" + time);
if (time > 59) {
mnts++;
mts.setText("" + mnts);
time = 0;
}
if (mnts > 59) {
hors++;
hrs.setText("" + hors);
mnts = 0;
}
} catch (InterruptedException e) {
}
}
}
public static void main(String[] args) {
new Ex1();
}
}
最佳答案
Swing 组件属性的更新应在 EDT 上完成。 mre 提供的上述链接将提供更多相关信息。确保在 EDT 上执行重复代码的一个简单方法是使用 Swing 计时器。
参见How to Use Swing Timers了解更多信息。
关于java - 秒表按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6928361/