最近,我开始学习Java FX。现在,我正在练习属性绑定。我现在使用Inetellij IDE。我有一个我无法解决的问题,我不明白哪里出了问题。我声明了一些属性,例如。 Person类中的StringProperty,还创建了构造函数,getter和setter。我试图绑定(或bindBidirectional)初始化方法中的那些属性,但我不能。当我将person.getNameProperty作为代码中的方法bind或bindBidirectional作为参数时(如代码中所示),将出现错误。有人可以帮我吗?我该怎么办?我看到了用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);
}
}


控制器:

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());


}
}


班级人员:

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文件看起来很好-我只是运行布局。

最佳答案

您不绑定到字符串,而是绑定到属性本身。

nameTextField.textProperty().bindBidirectional(person.namePropertyProperty());


并在这里提出一些个人意见;)IntelliJ是Java开发的最佳IDE。有一天的插头。

07-25 23:20
查看更多