【问题标题】:How to implement a constantly active loop to check for changes?如何实现一个不断活跃的循环来检查变化?
【发布时间】:2019-05-23 15:51:35
【问题描述】:

我在 "start" 方法中创建了一个空的 TextField test 和一个空的 TextField test2

public void start(Stage primaryStage) throws Exception {}

现在我想经常检查test.getText().equals("")。如果是,test2.setEditable(false),否则test2.setEditable(true)

我不知道如何实现它,因为它需要不断检查。

我已经尝试在start方法中实现一个if语句,它实际上在notEditable上设置了test2,因为test是空的,但是当test.getText().equals("")更改为!test.getText().equals("")@ 987654333@ 仍然不可编辑。

【问题讨论】:

    标签: loops user-interface intellij-idea javafx


    【解决方案1】:

    你可以只听这样的变化,而不是一直检查:

    test.textProperty().addListener((observable, oldValue, newValue) -> {
      if (newValue.equals("")) {
         test2.setEditable(false);
      } 
    
    );
    

    【讨论】:

    • 非常感谢。工作!
    • 太棒了!然后你可以将答案标记为正确的:)
    • 我相信,根据OP的问题,如果新值等于"",您还必须将test2的可编辑性设置为true。比如:test.textProperty().addListener((obs, ov, nv) -> test2.setEditable(nv != null && !nv.isEmpty()));.
    【解决方案2】:

    您可以通过将test2editable 属性绑定到testtext 属性来做到这一点。

    import javafx.application.Application;
    import javafx.geometry.Insets;
    import javafx.geometry.Pos;
    import javafx.scene.Scene;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class Main extends Application {
    
      @Override
      public void start(Stage primaryStage) {
        TextField test = new TextField();
        TextField test2 = new TextField();
    
        // do the binding
        test2.editableProperty().bind(test.textProperty().isEmpty().not());
    
        VBox root = new VBox(20, test, test2);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(50));
    
        primaryStage.setScene(new Scene(root, 300, 150));
        primaryStage.setTitle("Example");
        primaryStage.show();
      }
    
    
    }
    

    TextFieldtext 属性是 StringProperty。此类具有方法isEmpty(由StringExpression 继承)返回一个BooleanBinding,如果StringProperty 的值为空或null,则该true 将保持不变。 not() 调用否定了BooleanBinding 的值,这意味着test2 只有在test 的文本为空时才可编辑。

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 2021-11-13
      • 2017-07-17
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多