首页 > 解决方案 > 在按钮单击时添加字段

问题描述

我需要在按钮单击时添加一堆标签和文本字段。在这种情况下,我需要将它们作为代码添加,而不是在 FXML 中?

我有汽车类,当用户单击“添加汽车”按钮时,我必须添加 10 个标签和文本字段。有没有比这样添加它们更好的方法:

Label label = new Label("State registration number:");
TextField textField1 = new TextField();
Label label2 = new Label("Brand:");
TextField textField2 = new TextField();
Label label3 = new Label("Model:");
TextField textField3 = new TextField();
Label label4 = new Label("Year of production:");

等等......如果我需要向它们添加一些其他属性,我需要多写 30 多行。有没有更好的方法来做到这一点?最佳做法是什么?

标签: javajavafxlabel

解决方案


这不是最好的解决方案,而是一个很好的开始

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class MultipleLabelTextFiledApp extends Application {
    private final ObservableList<CustomControl> customControls = FXCollections.observableArrayList();
    private final List<String> labels = Arrays.asList("label1", "label2", "label3", "label4", "label5");

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

    @Override
    public void start(Stage stage) throws Exception {

        labels.stream().forEach(label -> customControls.add(new CustomControl(label)));

        VBox vBox = new VBox();
        vBox.getChildren().setAll(customControls);

        stage.setScene(new Scene(vBox));
        stage.show();

        getCustomControl("label1").ifPresent(customControl -> {
            customControl.getTextField().textProperty().addListener((ChangeListener<String>) (observable, oldValue, newValue) -> {
                System.out.println("textField with label1 handler new text=" + newValue);
            });
        });
    }

    private Optional<CustomControl> getCustomControl(String labelText) {
        return customControls.stream()
        .filter(customControl -> labelText.equals(customControl.getLabel().getText()))
        .findFirst();
    }
}

class CustomControl extends HBox {

    private final Label label = new Label();
    private final TextField textField = new TextField();

    {
        getChildren().addAll(label, textField);
    }

    public CustomControl(String text) {
        label.setText(text);
    }

    public Label getLabel() {
        return label;
    }

    public TextField getTextField() {
        return textField;
    }
}

推荐阅读