我正在尝试在 Java FX 中填充文本字段的值。
我有主类、 Controller 和 fxml。我已将 fxml 文件与 Controller 和其中的适当字段绑定(bind)。当我尝试设置它的值时,它失败了。
主.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);
}
}
测试 Controller .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>
最佳答案
你做错地方了!如果您需要在加载 fxml 之前使用控件,则需要在 initialize()
中执行此操作。 .为此,您的 Controller 应实现 Initializable
所以你的 Controller 变成了:
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");
}
}
关于Java FX 8,无法设置文本字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189984/