在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
對象的相應屬性將自動更新;反之亦然。