在下一个代码中应该有一个错误/遗漏,但我看不到主要是因为我从来没有使用过线程。有人可以找到我失踪的东西吗?这里有什么遗漏/错误?
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JDialog;
import javax.swing.JLabel;
public class JavaSwingTest extends JDialog {
private JLabel m_countLabel;
private Timer m_timer = new Timer();
private class IncrementCountTask extends TimerTask {
@Override
public void run() {
m_countLabel.setText(Long.toString(System.currentTimeMillis()
/1000));
}
}
private JavaSwingTest() {
createUI();
m_timer.schedule(new IncrementCountTask(), 1000, 1000);
}
private void createUI() {
Button button1 = new Button("Action1");
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
doLongOperation();
}
});
add(button1, BorderLayout.NORTH);
m_countLabel = new JLabel(Long.toString(System.currentTimeMillis()
/1000));
add(m_countLabel, BorderLayout.CENTER);
}
/**
* Simulates an operation that takes time to complete.
*/
private void doLongOperation() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// ignored for this test
}
}
/**
* @param args
*/
public static void main(String[] args) {
new JavaSwingTest().setVisible(true);
}
}
这个省略/错误是你省略了你问题的一部分,你告诉我们你想要解决的错误是什么。 – 2010-09-29 19:29:40
嗯。您正在设置线程(不是主线程(定时器))的Swing组件的值。 – Dirk 2010-09-29 19:33:52
@Dirk:'setText'是线程安全的极少数Swing方法之一。 – 2010-09-29 19:38:09