在JavaFX中,使用FXML进行数据绑定可以让你更容易地将数据与UI组件关联起来。以下是一个简单的示例,说明如何在JavaFX和FXML之间进行数据绑定:
Person
的类,其中包含firstName
和lastName
属性:import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Person {
private StringProperty firstName = new SimpleStringProperty();
private StringProperty lastName = new SimpleStringProperty();
public String getFirstName() {
return firstName.get();
}
public StringProperty firstNameProperty() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public String getLastName() {
return lastName.get();
}
public StringProperty lastNameProperty() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
}
Person
类中的属性进行绑定。例如,我们创建一个名为PersonView.fxml
的文件,其中包含两个文本字段,分别用于显示和编辑firstName
和lastName
属性:<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml">
<TextField fx:id="firstNameField" promptText="First Name" />
<TextField fx:id="lastNameField" promptText="Last Name" />
</VBox>
Person
类的实例进行绑定。例如,我们创建一个名为PersonController
的类,该类将加载FXML文件,并将其与Person
类的实例进行绑定:import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class PersonController {
@FXML
private TextField firstNameField;
@FXML
private TextField lastNameField;
private Person person;
public PersonController(Person person) {
this.person = person;
}
public void show() throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("PersonView.fxml"));
loader.setController(this);
Parent root = loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
}
@FXML
public void initialize() {
firstNameField.textProperty().bindBidirectional(person.firstNameProperty());
lastNameField.textProperty().bindBidirectional(person.lastNameProperty());
}
}
Person
对象,并使用PersonController
显示它:import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Person person = new Person();
person.setFirstName("John");
person.setLastName("Doe");
PersonController controller = new PersonController(person);
controller.show();
}
public static void main(String[] args) {
launch(args);
}
}
现在,当你运行此应用程序时,它将显示一个包含两个文本字段的窗口。这些文本字段将自动与Person
对象的firstName
和lastName
属性进行双向绑定。当你在文本字段中输入内容时,Person
对象的相应属性将自动更新;反之亦然。