Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaFx textfield.setText()方法不起作用_Java_Multithreading_Javafx - Fatal编程技术网

JavaFx textfield.setText()方法不起作用

JavaFx textfield.setText()方法不起作用,java,multithreading,javafx,Java,Multithreading,Javafx,JavaFx textfield.setText()方法不工作从另一个线程调用时,我正在从另一个线程调用received()方法。但是我无法将文本设置到文本字段,因此我使用了platform.runlater,但它不工作 DepartmentsController是我的控制器类,它接收了从另一个线程调用的方法(kryonet线程kryonet是一个高级网络库) 我有一个主类,它是javafx应用程序的开始,初始化包含javafx应用程序所有控制器的控制器类 import com.MyCompan

JavaFx textfield.setText()方法不工作从另一个线程调用时,我正在从另一个线程调用received()方法。但是我无法将文本设置到文本字段,因此我使用了platform.runlater,但它不工作

DepartmentsController是我的控制器类,它接收了从另一个线程调用的方法(kryonet线程kryonet是一个高级网络库)

我有一个主类,它是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();


    }
}
公共类DashBoardController实现可初始化{
SchemesController SchemesController;
主要的;
切换按钮[]tb,tb2;
亲本根;
图像视图iv0、iva0、iv1、iva1、iv2、iva2、iv3、iva3、iv4、iva4、iv5、iva5、iv6、iva6、iv7、iva7;
/**
*初始化控制器类。
*/
@凌驾
公共void初始化(URL、ResourceBundle rb){
System.out.println(“一次”);
公共无效启动(主)
{
this.main=main;
//tb=新的切换按钮[8];
tb2=新的切换按钮[8];
VBox up=新的VBox(20);
Text text4flow=新文本(“基本”);
text4flow.setFont(Font.Font(“Calibri”,fontwweight.BOLD,30));
text4flow.setFill(颜色为白色);
text4flow.setUnderline(false);
设置边距(text4flow,新的插入(10,0,0,10));
//创建流窗格
设置填充(新插图(50,50,50,50));
FlowPane FlowPane=新的FlowPane();
flowpane.setHgap(10);
flowpane.setVgap(10);
flowpane.getChildren().add(tb[1]);
tb[1]。addEventHandler(MouseEvent.MOUSE_输入,
新的EventHandler(){
@重写公共无效句柄(MouseEvent e){
tb[1]。已选择设置(true);
tb[1].设置图(iva1);
}
});
tb[1]。addEventHandler(MouseEvent.MOUSE_退出,
新的EventHandler(){
私人效应阴影;
@重写公共无效句柄(MouseEvent e){
tb[1].集落图(iv1);
}
});
tb[1].setOnAction(新的EventHandler(){
@重写公共无效句柄(ActionEvent e){
tb[1].设置图(iva1);
试一试{
系统输出打印LN(“kk”);
FXMLLoader=新的FXMLLoader();
setLocation(getClass().getResource(“Departments.fxml”);
窗格屏幕=(窗格)加载程序。加载();
main.controllers.departmentsController=loader.getController();
主控制器。部门控制器。启动(主);
StaticClass.stage.setFullScreen(真);
/*FadeTransition ft=新的FadeTransition(持续时间.毫秒(1000),屏幕);
ft.setFromValue(0.7);
ft.setToValue(1.0);
ft.play()*/
StaticClass.stage.getScene().setRoot(屏幕);
StaticClass.stage.getScene().getStylesheets().add(“com/MyCompany/UICoreComponents/JMetroDarkTheme.css”);
StaticClass.stage.show();
//在此处为事件执行一些代码。。
}捕获(IOEX异常){
Logger.getLogger(DashBoardController.class.getName()).log(Level.SEVERE,null,ex);
}
}
});
StaticClass.stage.getScene().setRoot(向上);
StaticClass.stage.getScene().getStylesheets().add(“com/MyCompany/UICoreComponents/JMetroDarkTheme.css”);
StaticClass.stage.show();
}
}

首先,请确保在初始化视图之前获取数据,我建议将“自定义初始值设定项”的代码放在实际初始值设定项中

然后尝试用任务替换Runnable,这是一个后台JavaFX线程,用于处理UI并将文本放置在文本字段中:

final Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            //code here
            return null;
        }
    };

new Thread(task).start();
final Task Task=新任务(){
@凌驾
受保护的Void调用()引发异常{
//代码在这里
返回null;
}
};
新线程(任务).start();

您可以阅读官方文档中关于任务的更多信息:

请显示代码的更多上下文。在控制器中定义了
接收到的
在哪里?从哪里调用?如果在控制器中定义了
,您如何获得对控制器的引用?我已添加了所有必要的信息…接收到的不是从co调用的controller它被称为form NetworkManager类,它本身是另一个线程。要引用控制器,我使用的是定义了所有控制器并引用了所有控制器的controllers类各个部分之间的关系仍然不是很清楚。您可能需要创建一个来获取帮助。(强调完整和最小化:不需要10个不同的视图来显示问题,但需要显示如何显示不响应方法调用的文本字段。)我建议从头开始写一个新的项目,它只足以显示问题。我真的很沮丧……要解决这个问题……我正在尝试设置departmentsId.setText()方法,我研究并发现我必须使用platform.runlater才能从另一个线程访问gui线程,但问题是它不起作用,我无法设置毫无意义的文本。因为您无法更改后台线程上的UI,并且如上所述,
Networkmanager
正在运行在后台线程上,OP正在使用
Platform.runLater(…)
计划在FX应用程序线程上的更改。使用
任务将其移动到不同的后台线程几乎没有帮助。对不起,James,你是什么意思?我完全按照我的回答使用任务来更改UI,我使用了不同/错误的概念吗?Y
final Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            //code here
            return null;
        }
    };

new Thread(task).start();