我正在尝试将 Spinner 的值绑定(bind)到整数属性。 This answer并不令人满意,因为我不想创建一个新的 IntegerProperty,而是将微调器的值绑定(bind)到现有的值。
我尝试创建一个新的 IntegerProperty,如该答案所示,然后将其绑定(bind)到现有的 IntegerProperty。但是,此示例代码不起作用:
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
StackPane pane = new StackPane();
IntegerProperty controlled = new SimpleIntegerProperty(); // I don't want to change this.
final Spinner<Integer> spinner = new Spinner<>(0, 10, 5, 1);
ObjectProperty<Integer> bridgeObject = new SimpleObjectProperty<>();
IntegerProperty bridgeInteger = IntegerProperty.integerProperty(bridgeObject); // "Returns a IntegerProperty that wraps a Property and is bidirectionally bound to it."
SpinnerValueFactory<Integer> valueFactory = spinner.getValueFactory(); // not null
ObjectProperty<Integer> integerObjectProperty = valueFactory.valueProperty(); // not null
integerObjectProperty.bindBidirectional(bridgeObject); // Throws NullPointerException, but not while debugging?!
bridgeInteger.bindBidirectional(controlled);
pane.getChildren().add(spinner);
primaryStage.setScene(new Scene(pane, 300, 275));
primaryStage.show();
}
}
问题:
- 是否有比创建两个中间“桥”属性更好的方法来绑定(bind)到现有
IntegerProperty
? - 如果没有,为什么我的示例代码会抛出 NullPointerException?我检查了
integerObjectProperty
不为空的断言。奇怪的是,如果逐行调试代码,则不会抛出异常(为什么?)。另一个问题的作者声称他已经成功完成了类似的操作,但没有回应其他用户发布代码的请求。
最佳答案
您的空指针异常可能是由于进行绑定(bind)时 bridgeObject.get()
为 null 所致。
你所需要的只是
@Override
public void start(Stage primaryStage) throws Exception {
StackPane pane = new StackPane();
IntegerProperty controlled = new SimpleIntegerProperty(); // I don't want to change this.
final Spinner<Integer> spinner = new Spinner<>(0, 10, 5, 1);
spinner.getValueFactory().valueProperty().bindBidirectional(controlled.asObject());
pane.getChildren().add(spinner);
primaryStage.setScene(new Scene(pane, 300, 275));
primaryStage.show();
}
关于java - 将 Spinner<Integer> 绑定(bind)到现有 IntegerProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724407/