最近我开始学习Java FX。现在我正在练习属性绑定(bind)。我现在使用 Inetellij IDE。我有一个无法解决的问题,我不明白出了什么问题。我声明了一些属性,例如。 Person 类中的 StringProperty 并创建了构造函数以及 getter 和 setter。我试图在初始化方法中绑定(bind)(或绑定(bind)双向)这些属性,但我不能。当我将(如代码中所示)person.getNameProperty 作为方法绑定(bind)或绑定(bind)双向的参数时,出现错误。有人能帮我解决这个问题吗?我应该怎么办?我在 Netbeans IDE 中看到了类似的代码,并没有出现这样的问题。
主要内容
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 350));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller :
import javafx.scene.control.TextField;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private TextField nameTextField;
//other declarations
private Person person = new Person();
@Override
public void initialize(URL location, ResourceBundle resources) {
nameTextField.textProperty().bindBidirectional(person.getNameProperty());
}
}
类(class)人员:
package sample;
import javafx.beans.property.*;
import java.time.LocalDate;
/**
* Created by User on 2018-02-16.
*/
public class Person {
//person's name
private StringProperty nameProperty = new SimpleStringProperty();
//Other properties
//consturctor
public Person() {
}
public String getNameProperty() {
return nameProperty.get();
}
public StringProperty namePropertyProperty() {
return nameProperty;
}
public void setNameProperty(String nameProperty) {
this.nameProperty.set(nameProperty);
} }
FXML 文件看起来不错 - 我只是运行布局。
最佳答案
您不会绑定(bind)到绑定(bind)到属性本身的字符串。
nameTextField.textProperty().bindBidirectional(person.namePropertyProperty());
并在此提出一些个人观点;)IntelliJ 是 Java 开发的最佳 IDE。这是您当天使用的插头。
关于Java FX 绑定(bind)属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48830501/