使用侦听器动态添加文本字段

时间:2018-04-24 14:37:29

标签: java javafx

我正在尝试使用javafx在Android手机上编写类似于联系人应用程序的程序。在fxml文件中,我有一个包含三个文本字段的VBox,前两个字段用于名字和姓氏,第三个字段用于数字。

现在我想让程序做的是当数字的文本字段甚至用单个字符填充时,另一个文本字段将被自动添加到VBox中。 (换另一个号码)。

我想要为下一个领域发生同样的事情。以及随后的任何其他字段,因此它具有递归形式。

现在我知道可能实现此目的的唯一方法是使用侦听器,但我不知道如何创建这样的递归侦听器。并且一旦完成其工作就必须删除旧字段的监听器,因此在旧字段中键入内容时不会连续创建新字段。但是当你进入它时你无法删除它。

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:1)

lambda表达式不能引用自身,但是匿名内部类可以,因此如果您将侦听器实现为匿名内部类,则可以实现您想要执行的操作:

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class DynamicTextFields extends Application {

    private TextField lastTextField ;

    @Override
    public void start(Stage primaryStage) {
        lastTextField = new TextField();
        VBox vbox = new VBox(5, lastTextField);
        ChangeListener<String> textFieldListener = new ChangeListener<String>() {

            @Override
            public void changed(ObservableValue<? extends String> obs, String oldValue, String newValue) {
                lastTextField.textProperty().removeListener(this);
                lastTextField = new TextField();
                lastTextField.textProperty().addListener(this);
                vbox.getChildren().add(lastTextField);
            }

        };
        lastTextField.textProperty().addListener(textFieldListener);

        Scene scene = new Scene(new ScrollPane(vbox), 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

答案 1 :(得分:1)

ChangeListener注册到text的{​​{1}}属性,每次文本从空变为非时,根据索引添加/删除TextField空的或相反的。

TextField
public void addTextField(Pane parent) {
    TextField textField = new TextField();
    textField.textProperty().addListener((o, oldValue, newValue) -> {
        boolean wasEmpty = oldValue.isEmpty();
        boolean isEmpty = newValue.isEmpty();

        if (wasEmpty != isEmpty) {
            if (wasEmpty) {
                // append textfield if last becomes non-empty
                if (parent.getChildren().get(parent.getChildren().size() - 1) == textField) {
                    addTextField(parent);
                }
            } else {
                int tfIndex = parent.getChildren().indexOf(textField);
                if (tfIndex < parent.getChildren().size() - 1) {
                    // remove textfield if this is not the last one
                    parent.getChildren().remove(tfIndex);
                    parent.getChildren().get(tfIndex).requestFocus();
                }
            }
        }
    });

    parent.getChildren().add(textField);
}