我想用javafx同時執行多個倒計時定時器。目前使用多線程。現在我正試圖在標籤上打印定時器,以便在屏幕上顯示,但無法這樣做,因爲我無法訪問控制器類來打印它。我如何實現使用我的線程類打印標籤上的計時器值。我的計時器值應該打印在gridpane中的標籤中,所以我從控制器類中獲取約束,然後相應地打印。JavaFX多線程和控制器類
package tabapplication;
import java.util.Timer;
import java.util.TimerTask;
import tabapplication.TabApplication;
import tabapplication.FXMLDocumentController;
class Rdt implements Runnable {
private Thread t;
private String threadName;
Rdt(String name){
threadName = name;
System.out.println("Creating " + threadName);
}
public void run() {
System.out.println("Running " + threadName);
try {
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int s = 60;
int m=30;
public void run() {
s--;
if(s<0 && m>0)
{m--;
s=59;
}
if(s<10)
{ System.out.println(Integer.toString(m)+":"+0+Integer.toString(s)); }
else
{System.out.println(Integer.toString(m)+":"+Integer.toString(s));}
if(m==0 && s==0)
timer.cancel();
}
}, 0, 10);
Thread.sleep(50);
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start()
{
System.out.println("Starting " + threadName);
if (t == null)
{
t = new Thread (this, threadName);
t.start();
}
}
public static void main(String args[]) {
Rdt R1 = new Rdt("Thread-1");
Thread obj1=new Thread(R1);
obj1.start();
Rdt R2 = new Rdt("Thread-2");
Thread obj2=new Thread(R2);
obj2.start();
}
}
「我無法訪問控制器類...「。爲什麼不?推測在你的JavaFX應用程序中,你實際上會從控制器實例化這些定時器*(例如,作爲對用戶操作的響應)。 –
我希望計時器能夠獨立同時運行,但在我的情況下,只有一次運行和其他停止。這就是爲什麼我爲不同的定時器使用線程。我從上面提到的Java代碼調用fxml控制器。但我必須將每個計時器放在網格中的特定位置。無法實現這一點。 –