您的
StopWatch课程运行一次,然后终止…
public void run() { // Start here SwingUtilities.invokeLater(new Runnable() { @Override public void run() { long time = getElapsedTime(); sidePanel.this.clock.setText(String.valueOf(time)); } }); // End here...}线程将在存在于其
run方法时终止,在本例中为您
StopWatch的
run方法。
你需要做的,什么是维持一个循环,直到
isRunning变成
false
public void run() { while (isRunning) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { long time = getElapsedTime(); sidePanel.this.clock.setText(String.valueOf(time)); } }); // Because we really don't want to bombboard the Event dispatching thread // With lots of updates, which probably won't get rendered any way, // We put in a small delay... // This day represents "about" a second accuracy... try { Thread.sleep(500); } catch (Exception exp) { } }}javax.swing.Timer尽管使用… 会更简单…
private Timer timer;public void init(){ pane = new JPanel(); pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); clock = new JLabel("00:00"); toggle = new JButton("Start/Stop"); toggle.addActionListener(this); pane.add(clock); pane.add(toggle); timer = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent evt) { long time = getElapsedTime(); sidePanel.this.clock.setText(String.valueOf(time)); } }); timer.setRepeats(true); add(pane);}@Overridepublic void actionPerformed(ActionEvent e) { if(e.getSource() == toggle) { if(timer.isRunning()) { endTime = System.currentTimeMillis(); timer.stop(); } else { startTime = System.currentTimeMillis(); timer.start(); } }}然后,您可以从中剥离功能
StopWatch(即
getElapsedTime())



