JavaFx textfield.setText()方法从另一个线程调用时不工作,我从另一个线程调用recieved()方法。但是我无法将文本设置为文本字段,所以我使用了platform.runlater但是它不起作用。
DepartmentsController是我的控制器类,它具有从另一个线程调用的接收方法(kryonet线程-Kryonet是一个高级网络库)。
import com.MyCompany.Modal.DepartmentModal;
import com.MyCompany.Network.ClientMaster;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.FadeTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
public class DepartmentsController implements Initializable {
private DepartmentModal departmentModal;
@FXML
Button btn;
@FXML
VBox vBox;
@FXML
ComboBox departmentNameComboBox;
@FXML
TextField departmentNameTF;
@FXML
TextField departmentIdTF;
@FXML
TextField noOfBatchTF;
Main main;
public void customInitialize()//initialize from controllers
{ departmentModal.setRequestData(true);
ClientMaster.NETWORK_MANAGER.client.sendTCP(departmentModal);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
departmentModal=new DepartmentModal();
//String string = new StringBuilder("abcd").append(23).append(false).append("xyz").toString();
TranslateTransition tt = new TranslateTransition(Duration.millis(700),btn);
tt.setFromX(-100);
tt.setToX(0f);
tt.setCycleCount((int) 1f);
tt.setAutoReverse(false);
tt.play();
FadeTransition ft = new FadeTransition(Duration.millis(1000), vBox);
ft.setFromValue(0);
ft.setToValue(1.0);
ft.play();
}
public void initiate(Main main)
{
this.main=main;
}
public void backBtnOnClick()
{
main.controllers.dashBoardController.Initiate(main);
System.out.println("clicked");
}
public void saveBtnOnClick()
{
}
public void clearBtnOnClick()
{
}
public void recieved(DepartmentModal departmentModal)
{
if(departmentModal.isRequestData()==true)
{
Platform.runLater(new Runnable() {
@Override
public void run() {
System.out.println(departmentModal.getDepartmentId());
departmentIdTF.setText(departmentModal.getDepartmentId());//cannot set this field
}
});
}
}
}
我有一个javafx应用程序启动的主类初始化包含我的javafx应用程序的所有控制器的控制器类
import com.MyCompany.Network.ClientMaster;
import javafx.animation.ScaleTransition;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* @author shersha
*/
public class Main extends Application {
public Controllers controllers;
@Override
public void start(Stage stage) throws Exception {
controllers=new Controllers();
new StaticClass(stage);
new ClientMaster(this);
Screen screen = Screen.getPrimary();
Rectangle2D bounds = screen.getVisualBounds();
StaticClass.stage.setX(bounds.getMinX());
StaticClass.stage.setY(bounds.getMinY());
StaticClass.stage.setWidth(bounds.getWidth());
StaticClass.stage.setHeight(bounds.getHeight());
controllers.loginController.initialize(this);
Scene scene = new Scene(controllers.loginLoader.getRoot());
scene.getStylesheets().add("com/MyCompany/UICoreComponents/JMetroDarkTheme.css");
/*FadeTransition ft = new FadeTransition(Duration.millis(2000), controllers.loginLoader.getRoot());
ft.setFromValue(0.5);
ft.setToValue(1.0);
ft.play();*/
/* TranslateTransition tt = new TranslateTransition(Duration.millis(2000), controllers.loginLoader.getRoot());
tt.setByX(200f);
tt.setCycleCount((int) 4f);
tt.setAutoReverse(true);
tt.play();*/
ScaleTransition st = new ScaleTransition(Duration.millis(1000), controllers.loginLoader.getRoot());
st.setFromX(1.5f);
st.setFromY(1.5f);
st.setToX(1f);
st.setToY(1f);
st.setCycleCount((int) 1f);
st.setAutoReverse(true);
st.play();
StaticClass.stage.setFullScreen(true);
StaticClass.stage.setScene(scene);
StaticClass.stage.setFullScreenExitHint("");
//StaticClass.stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
StaticClass.stage.show();
/*
StaticClass.stage.setScene(StaticClass.LOGIN_SCENE);
StaticClass.stage.setFullScreen(true);
StaticClass.stage.setFullScreenExitHint("");
StaticClass.stage.show();
*/
}
public static void main(String[] args) {
launch(args);
}
}
Controllers类创建引用departmentscontroller,以便我可以从任何控制器(如
)访问它main.controllers.departmentcontroller
import javafx.fxml.FXMLLoader;
/**
*
* @author Shersha
*/
public class Controllers {
public LoginController loginController;
public DepartmentsController departmentsController;
public DashBoardController dashBoardController;
public SchemeDepartmentController schemeDepartmentController;
public StaffsController staffsController;
public SchemesController schemesController;
public SubjectsController subjectsController;
public StudentsController studentsController;
public StaffManagementController staffManagementController;
public StudentManagementController studentManagementController;
FXMLLoader staffManagementLoader,studentManagementLoader,subjectsLoader,studentsLoader,loginLoader,dashBoardLoader,schemesLoader,departmentsLoader,schemeDepartmentLoader,staffsLoader;
public Controllers() throws Exception
{
loginLoader= new FXMLLoader();
loginLoader.setLocation(getClass().getResource("Login.fxml"));
loginLoader.load();
loginController= loginLoader.getController();
dashBoardController= new DashBoardController();
schemesLoader= new FXMLLoader();
schemesLoader.setLocation(getClass().getResource("Schemes.fxml"));
schemesLoader.load();
schemesController= schemesLoader.getController();
departmentsLoader= new FXMLLoader();
departmentsLoader.setLocation(getClass().getResource("Departments.fxml"));
departmentsLoader.load();
departmentsController=departmentsLoader.getController();
schemeDepartmentLoader= new FXMLLoader();
schemeDepartmentLoader.setLocation(getClass().getResource("SchemeDepartment.fxml"));
schemeDepartmentLoader.load();
schemeDepartmentController=schemeDepartmentLoader.getController();
staffsLoader= new FXMLLoader();
staffsLoader.setLocation(getClass().getResource("Staffs.fxml"));
staffsLoader.load();
staffsController=staffsLoader.getController();
subjectsLoader= new FXMLLoader();
subjectsLoader.setLocation(getClass().getResource("Subjects.fxml"));
subjectsLoader.load();
subjectsController=subjectsLoader.getController();
studentsLoader= new FXMLLoader();
studentsLoader.setLocation(getClass().getResource("Students.fxml"));
studentsLoader.load();
studentsController=studentsLoader.getController();
staffManagementLoader= new FXMLLoader();
staffManagementLoader.setLocation(getClass().getResource("StaffManagement.fxml"));
staffManagementLoader.load();
staffManagementController=staffManagementLoader.getController();
studentManagementLoader= new FXMLLoader();
studentManagementLoader.setLocation(getClass().getResource("StudentManagement.fxml"));
studentManagementLoader.load();
studentManagementController=studentManagementLoader.getController();
}
public void initialize()
{
departmentsController.customInitialize();
}
}
NetworkManager(kryonet线程)是在departmentscontroller中调用recive方法的类
import com.MyCompany.Modal.DepartmentModal;
import com.MyCompany.Modal.LoginModal;
import com.MyCompany.Modal.SchemeModal;
import com.MyCompany.attendanceMaster.StaticClass;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import java.io.IOException;
import com.MyCompany.attendanceMaster.Main;
/**
*
* @author shersha
*/
public class NetworkManager extends Listener{
String ip = "localhost";
public Client client;
int port = 27960;
Main main;
RegisterClasses registerClasses;
public NetworkManager(Main main)
{
this.main=main;
}
public void connect(){
client = new Client();
registerClasses=new RegisterClasses(client);
client.addListener(this);
client.start();
try {
client.connect(5000, ip, port, port);
} catch (IOException e) {
e.printStackTrace();
System.out.println("server offline");
}
}
public void received(Connection c, Object o){
if(o instanceof LoginModal){
LoginModal loginModal=(LoginModal)o;
main.controllers.loginController.recieved(loginModal);
}
else if(o instanceof SchemeModal)
{
SchemeModal schemeModal=(SchemeModal)o;
main.controllers.schemesController.recieved(schemeModal);
}
else if(o instanceof DepartmentModal)
{
System.out.println("point 1");
DepartmentModal departmentModal=(DepartmentModal)o;
main.controllers.departmentsController.recieved(departmentModal);
}
}
}
我还有一个名为dashboard controller的类,它将所有fxml元素放到舞台上
public class DashBoardController implements Initializable {
SchemesController schemesController;
Main main;
ToggleButton[] tb,tb2;
Parent root ;
ImageView iv0,iva0,iv1,iva1,iv2,iva2,iv3,iva3,iv4,iva4,iv5,iva5,iv6,iva6,iv7,iva7;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
System.out.println("one time");
public void Initiate(Main main)
{
this.main=main;
// tb=new ToggleButton[8];
tb2=new ToggleButton[8];
VBox up = new VBox(20);
Text text4flow = new Text("Basic");
text4flow.setFont(Font.font("Calibri", FontWeight.BOLD, 30));
text4flow.setFill(Color.WHITE);
text4flow.setUnderline(false);
VBox.setMargin(text4flow, new Insets(10, 0, 0, 10));
//creating Flow Pane
up.setPadding(new Insets(50, 50, 50, 50));
FlowPane flowpane = new FlowPane();
flowpane.setHgap(10);
flowpane.setVgap(10);
flowpane.getChildren().add(tb[1]);
tb[1].addEventHandler(MouseEvent.MOUSE_ENTERED,
new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent e) {
tb[1].setSelected(true);
tb[1].setGraphic(iva1);
}
});
tb[1].addEventHandler(MouseEvent.MOUSE_EXITED,
new EventHandler<MouseEvent>() {
private Effect shadow;
@Override public void handle(MouseEvent e) {
tb[1].setGraphic(iv1);
}
});
tb[1].setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
tb[1].setGraphic(iva1);
try {
System.out.println("kk");
FXMLLoader loader= new FXMLLoader();
loader.setLocation(getClass().getResource("Departments.fxml"));
Pane screen = (Pane) loader.load();
main.controllers.departmentsController=loader.getController();
main.controllers.departmentsController.initiate(main);
StaticClass.stage.setFullScreen(true);
/* FadeTransition ft = new FadeTransition(Duration.millis(1000), screen);
ft.setFromValue(0.7);
ft.setToValue(1.0);
ft.play();*/
StaticClass.stage.getScene().setRoot(screen);
StaticClass.stage.getScene().getStylesheets().add("com/MyCompany/UICoreComponents/JMetroDarkTheme.css");
StaticClass.stage.show();
//Execute some code here for the event..
} catch (IOException ex) {
Logger.getLogger(DashBoardController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
StaticClass.stage.getScene().setRoot(up);
StaticClass.stage.getScene().getStylesheets().add("com/MyCompany/UICoreComponents/JMetroDarkTheme.css");
StaticClass.stage.show();
}
}
答案 0 :(得分:-1)
首先,请确保在初始化视图之前获取数据,我建议将“自定义初始化程序”的代码放在实际的初始化程序中...
然后尝试使用Task替换Runnable,它是一个后台JavaFX线程,用于处理UI并将Text放在TextField中:
final Task task = new Task<Void>() {
@Override
protected Void call() throws Exception {
//code here
return null;
}
};
new Thread(task).start();
您可以在官方文档中了解有关任务的更多信息:https://docs.oracle.com/javafx/2/api/javafx/concurrent/Task.html