i have got a question: i have got a simple Java FX Application where i have a button and when i hit the button a thread task starts which have to change a label every second:
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 is the standart one
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
}
}
So my question is, how i am able to access the setLabel Method from the CheckSystemTime class? i hope you are able to help me how i can solve this problem
Add the MyController
or a Label
or the textProperty
of the Label
to the constructor of CheckSystemTime
. Then you can keep a local reference inside CheckSystemTime
. Then you can access it inside your run method. But make sure to wrap every UI related calls inside Platform.runLater()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.