使用带有FXML的

时间:2017-06-24 01:45:04

标签: java javafx textfield

我正在寻找一种方法,允许用户通过点击创建按钮添加多个TextFields,然后为每个创建的TextField我想将其与删除按钮相关联,以允许用户删除任何Textfields。

这是我到目前为止遇到的情况。

@FXML
    private VBox pane_main_grid;
@FXML
private void AddTextField(ActionEvent event)  {     
 TextField newField = new TextField();
 pane_main_grid.getChildren().add(newField);}

如何跟踪创建的内容与我要删除的内容? 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以在其旁边添加一个按钮将其删除:

@FXML
private void AddTextField(ActionEvent event) {
    final HBox parent = new HBox(5.0); // 5.0 is the distance between the field and the button; hbox is the parent of both

    TextField field = new TextField();
    Button button = new Button("Close"); // the button to "close" the textfield
    button.setOnAction((e) -> pane_main_grid.getChildren().remove(parent)); // button click removes the hbox
    button.setPrefSize(100, 27); // only if you're using a custom font / styling
    HBox.setHgrow(field, Priority.ALWAYS); // field should always grow
    HBox.setHgrow(button, Priority.NEVER); // button should never grow

    parent.getChildren().setAll(field, button); // add the textfield and the button to the hbox
    pane_main_grid.getChildren().add(parent); // add the hbox to your main grid
}

答案 1 :(得分:0)

这样的东西?

private void AddTextField(ActionEvent event) {
    final TextField newField = new TextField();
    pane_main_grid.getChildren().add(newField);

    final Button deleteBtn = new Button("delete");
    pane_main_grid.getChildren().add(deleteBtn);
    deleteBtn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Platform.runLater(new Runnable() {

                @Override
                public void run() {
                    pane_main_grid.getChildren().remove(newField);
                    pane_main_grid.getChildren().remove(deleteBtn);
                }
            });           
        }
    });
}