当前位置: 首页 > 知识库问答 >
问题:

JavaFx文本字段。setText()方法不起作用

韩良策
2023-03-14

JavaFx文本字段。setText()方法不工作当从另一个线程调用时,我正在从另一个线程调用received()方法。但我无法将文本设置为文本字段,所以我使用了平台。稍后运行,但它不起作用。

DepartmentsController是我的控制器类,它接收了从另一个线程调用的方法(kryonet thread 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 thread)是在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();


    }
}

共有1个答案

诸葛奇玮
2023-03-14

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

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

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

 类似资料:
  • 我无法设置TextField的文本。没有错误,但Textfield仍然为空。程序的其余部分正在工作,方法被调用,system.out.println(...)打印正确的文本。所以问题是,不能设置textfield的文本。即使我只是写textfield.settext(“0”);textfield仍然为空。当我在public void initialize(...)下为textfield设置文本时也

  • 问题内容: 我可以使用setText(“åäö”),但是如果我没有在键盘上键入内容,这也不起作用 奇怪的是,它在Mac上不起作用,但在Windows上却起作用,有人对此有答案吗?谢谢! 这是另一个主题相似的问题! 如何从Libgdx中的特殊字符获取输入? 我试图获得ascii值并将其通过 但这不起作用。我将项目编码设置为UTF-8,并且可以打印åäö等特殊字符。 编辑:我尝试了 没有打印åäö 问

  • 我正在从事一个JavaFX 2.2项目,在使用TextField控件时遇到问题。我想限制用户可以在每个文本字段中输入的字符数。但是,我找不到属性或类似maxlength的东西。Swing中也存在同样的问题,通过这种方式解决了。JavaFX 2.2如何解决这个问题?

  • 我需要一些帮助。我有一个s的。 我想检查值是否发生了变化。如果是,我想知道它是哪个文本字段。我知道我可以使用侦听器来执行此操作,但这只适用于单个侦听器。 我希望它在数组上工作并确定哪个文本字段已更改。 提前感谢!

  • 我的代码中有JavaFX文本字段,希望在文本字段上为不同的事件添加一个操作。 今天,我只在文本字段中写入一些文本后按enter键时得到一个操作。如何添加处理tab press的操作?还有,当文本字段用鼠标点击失去焦点时,该如何反应? 当我读留档应该是可能的:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextFi

  • 我想确保用户在JavaFX TextField(0.0.0.0255.255.255.255)中输入有效的IPv4地址,但我似乎找不到任何有效的解决方案。 我尝试了该代码: 但是我连一个数字都打不出来...它似乎只用一个输入就可以工作