class runnable implements Runnable {
private Object obj;
public runnable(Object obj)
{
this.obj = obj;
}
public void run() {
try {
Thread.sleep(3000);
this.obj.setText("");//right here just execute your method
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello from a thread!"); //your code here
}
}
public class Test {
public static void main(String[] args){
Object myObject;
(new Thread(new runnable(myObject))).start();
}
}
你可以啓動另一個線程來處理這個問題。只要在另一個線程中進行處理即可。睡3秒鐘,然後清除lbl。
這裏有一個例子展示它是如何工作的:
class runnable implements Runnable {
Test test;
public runnable(Test test)
{
this.test = test;
}
public void run() {
try {
Thread.sleep(3000);
this.test.test = "test2";
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello from a thread!");
}
}
public class Test {
public String test = "test";
public static void main(String[] args) throws InterruptedException{
Test test = new Test();
System.out.println(test.test);
(new Thread(new runnable(test))).start();
Thread.sleep(4000);
System.out.println(test.test);
}
}
****************************** ****************************** UPDATE ******************* ******************************************
class runnable implements Runnable {
Test test;
public runnable(Test test)
{
this.test = test;
}
public void run() {
try {
Thread.sleep(3000);
this.test.label.setText("This is a test.");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Hello from a thread!");
}
}
public class Test {
public String test = "test";
JLabel label = new JLabel("Test");
JFrame frame = new JFrame();
JButton button = new JButton();
public static void main(String[] args) throws InterruptedException{
Test test = new Test();
test.label.setText("Test");
test.button.setText("Test Button");
test.button.setSize(50, 50);
test.frame.setSize(500, 500);
test.frame.add(test.button);
test.frame.add(test.label);
test.frame.setVisible(true);
test.button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
});
(new Thread(new runnable(test))).start();
}
}
我沒有得到這個編譯錯誤,但後續運行時錯誤:線程「定時器0」中的異常java.lang.IllegalStateException:不在FX應用程序線程; currentThread = Timer-0 – 2014-12-03 21:31:21
哦。如果您使用的是javafx,則必須使用Platform.runLater()處理此問題才能在gui線程中運行您的代碼。我更新了我的文章 – Deton 2014-12-03 22:06:23
感謝您的時間:)我現在得到這個編譯錯誤:錯誤:找不到符號 Platform.runLater(new Runnable(){ symbol:variable Platform – 2014-12-03 22:08:33