我试图将Spinner的值绑定到整数属性。 This answer并不令人满意,因为我不想创建新的IntegerProperty,而是将微调器的值绑定到现有的值。
我尝试创建一个新的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();
}
}
问题:
IntegerProperty
,而不是创建两个中间的&#34; bridge&#34;属性?integerObjectProperty
不为空的断言。奇怪的是,如果代码是逐行调试的,那么不会抛出异常(为什么?)。另一个问题的作者声称他已经成功完成了这样的事情,但没有回复另一个用户发布代码的请求。答案 0 :(得分:2)
您的空指针异常可能是由于bridgeObject.get()
在您进行绑定时为空。
你需要的只是
@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();
}