绑定list.contains()方法的结果

时间:2015-06-09 08:48:43

标签: java binding javafx javafx-8

我想绑定文本字段以指示整数列表是否包含1。 我有一个按钮,在列表中插入1,我希望文本字段将更新,但这不会发生。为什么以及如何修复它?

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Hello World!");
    final List<Integer> list = new ArrayList<Integer>();
    Button btn = new Button();
    btn.setText("Say 'Hello World'");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            list.add(1);
        }
    });
    TextField txt = new TextField();
    txt.textProperty().bind(new SimpleStringProperty(String.valueOf(list.contains(1))));
    VBox root = new VBox();
    root.getChildren().addAll(btn,txt);
    primaryStage.setScene(new Scene(root, 300, 250));
    primaryStage.show();
}

1 个答案:

答案 0 :(得分:1)

尝试创建一个BooleanBinding:

@Override
public void start( final Stage primaryStage )
{

    primaryStage.setTitle( "Hello World!" );
    final List<Integer> list = new ArrayList<>();

    // we need an ObservableList, duh, to observe!
    final ObservableList<Integer> oblist = FXCollections.observableArrayList( list );
    Button btn = new Button();
    btn.setText( "Say 'Hello World'" );
    btn.setOnAction( new EventHandler<ActionEvent>()
    {
        @Override
        public void handle( ActionEvent event )
        {
            oblist.add( 1 );
        }
    } );
    BooleanBinding bb = Bindings.createBooleanBinding( () -> oblist.contains( 1 ), oblist );

    TextField txt = new TextField();
    txt.textProperty().bind( bb.asString() );
    VBox root = new VBox();
    root.getChildren().addAll( btn, txt );

    final Scene scene = new Scene( root, 400, 300 );
    primaryStage.setScene( scene );
    primaryStage.show();
}
  

我仍然不明白我的代码有什么问题,你能解释一下吗?   我好吗?

让我们分解代码:new SimpleStringProperty(String.valueOf(list.contains(1)));

- &GT;最初list.contains(1) =假
- &GT; String.valueOf(false) =&#34; false&#34;
- &GT; new SimpleStringProperty("false")将创建具有初始值&#34; false&#34;的StringProperty的新实例,并且此实例绑定到textField的textProperty。就是这样,因为我们使用字符串值&#34; false&#34;开始,没有进一步观察list及其包含1或不包含1的内容。因此,我们需要一个可观察的列表。

因此,如果更改了绑定的StringProperty,则文本字段的文本将同步更改。重写为,

StringProperty sp = new SimpleStringProperty(String.valueOf(list.contains(1)));
txt.textProperty().bind(sp);
sp.set("newVal"); // at this point textfield's text will be updated with 
// "newVal", but it has nothing about list and its content.