日期:2014-05-19  浏览次数:20613 次

使用线程使每隔一段时间改变一下JLabel的值
package com.thread;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FrameDemo extends JFrame{
int str=0;
 JLabel jtf=new JLabel("0");
public FrameDemo() {
init();
}
public void init() {
this.setTitle("扫雷记时所用");
this.setBounds(200, 200, 200, 200);
this.add(createMain());
this.setVisible(true);
}
private JPanel createMain() {
JPanel jp=new JPanel();
JLabel jl=new JLabel("时间:");
Button start=new Button("开始");
Button toggle=new Button("切换");
jtf.setEnabled(false);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(1000);
jtf.setText(Integer.toString(str++));
System.out.println(str);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.run();
}
});
jp.add(jl);
jp.add(jtf);
jp.add(start);
jp.add(toggle);
return jp;
}
public static void main(String[] args) {
new FrameDemo();
}

}


------解决方案--------------------
因为你根本就没有启动线程,而是把主GUI线程给阻塞了。。。

这段:
new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(1000);
jtf.setText(Integer.toString(str++));
System.out.println(str);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.run();

改为:
Java code
new Thread() {
  public void run() {
    while(true){
      try {
        Thread.sleep(1000);
        jtf.setText(Integer.toString(str++));
        System.out.println(str);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}.start();

------解决方案--------------------
LS正解,, lz要记得启动线程是start()方法。