【发布时间】:2018-02-13 21:37:18
【问题描述】:
我有一个问题: 我有一个简单的 Java FX 应用程序,其中有一个按钮,当我按下按钮时,一个线程任务启动,它必须每秒更改一个标签:
MyController.java
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeUnit.*;
import java.util.*;
import java.text.DateFormat;
public class MyController implements Initializable{
@FXML
private Button myButton;
@FXML
private TextField myCountry;
@FXML
public Label myTime;
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
public void startTimeThread(ActionEvent event) {
ScheduledThreadPoolExecutor eventPool = new ScheduledThreadPoolExecutor(3);
eventPool.scheduleAtFixedRate
(new CheckSystemTime(), 0, 2, TimeUnit.SECONDS);
myButton.setDisable(true);
}
public void setLabel(String text) {
myTime.setText(text);
}
}
Main.java 是标准的
CheckSystemTime.java
package application;
import java.util.*;
import java.text.DateFormat;
public class CheckSystemTime implements Runnable {
//String locale;
public CheckSystemTime(/**String location**/) {
//this.locale = location;
}
public void run() {
Date rightNow;
DateFormat timeFormatter;
String timeOutput;
rightNow = new Date();
Locale currentLocale = new Locale("de");
timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, currentLocale);
timeOutput = timeFormatter.format(rightNow);
//e.g. MyController.setLabel(timeOutput); doesnt work
}
}
所以我的问题是,我如何能够从 CheckSystemTime 类访问 setLabel 方法? 我希望你能帮助我如何解决这个问题
【问题讨论】:
-
在您的
MyController.java中,您使用new Main()调用eventPool.scheduleAtFixedRate。这应该是new CheckSystemTime()。
标签: java multithreading javafx