Java FX 8,设置文本字段的值时出错

时间:2014-10-04 05:30:57

标签: java javafx javafx-8

我正在尝试填充Java FX中文本字段的值。

我有Main Class,控制器和fxml.I已将fxml文件与控制器及其中的相应字段绑定。当我尝试设置其值时,它会失败。

Main.java

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;


public class Main extends Application {

    private Stage primaryStage;
    private FlowPane rootLayout;

    @Override
    public void start(Stage primaryStage) {
        try {


            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(Main.class.getResource("test.fxml"));            
            rootLayout = (FlowPane) loader.load();                      
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();



        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

testController.java

package application;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;

public class testController {

    @FXML
    private TextField t1;

    public testController() {

        System.out.println("hi");
        t1 = new TextField("j");
        t1.setText("hi");

    }



}

FXML文件:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.FlowPane?>

<FlowPane prefHeight="200.0" prefWidth="200.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.testController">
   <children>
      <TextField fx:id="t1" />
   </children>
</FlowPane>

1 个答案:

答案 0 :(得分:5)

你是在错误的地方做的!如果您需要在加载fxml之前使用控件,则需要在initialize()中执行此操作。为此,您的控制器应实现Initializable

所以你的控制器变成了:

public class testController implements Initializable{

    @FXML
    private TextField t1;

    public void initialize() {

        System.out.println("hi");

        //You should not re-initialize your textfield
        //t1 = new TextField("j");

        t1.setText("hi");

    }
}