JavaFx: создание поля ввода текста - PullRequest
0 голосов
/ 27 ноября 2018

Я работаю над проектом textEditor и хотел бы создать оконную подсказку типа TextInputDialog, которая может принимать вводимый текст из TextArea (я хочу, чтобы это был TextArea вместо TextField) и возвращать строку ввода.У меня также есть кнопка в GUI, который я создал.При нажатии на кнопку необходимо вернуть строку в TextArea и закрыть окно графического интерфейса.

    public String CommentWindow(String selectedText){
    Stage commentWindow = new Stage();
    VBox box = new VBox(20);
    TextArea commentbox = new TextArea();
    Label commentlabel = new Label("Enter the annotation for " + 
    selectedText + " :");
    Button addComment = new Button("Add annotation");
    box.getChildren().addAll(commentlabel,commentbox,addComment);
    commentWindow.setScene(new Scene(box,350,250));
    commentWindow.show();
    String comment = commentbox.getText();
    return comment;
}

Проблема со следующим кодом заключается в том, что я не знаю, как убедиться, что строка вTextArea возвращается после нажатия кнопки, а также необходимо закрыть окно.Я довольно новичок в JavaFx, поэтому, пожалуйста, извините меня за стиль кода.

Вот изображение GUI: Окно комментариев

РЕДАКТИРОВАТЬ 1: Я нехотите использовать любые функции диалога или оповещения JavaFx.Я в основном пытаюсь построить что-то подобное самостоятельно.Я просто хочу, чтобы окно графического интерфейса, которое я строю, возвращало строку ввода текста в текстовой области и закрывало окно после нажатия кнопки.Может кто-нибудь предложить мне, как написать код для этого?

1 Ответ

0 голосов
/ 27 ноября 2018

У вас есть несколько вариантов для этого, но я представлю один из них.Если вы ищете только TextArea в TextInputDialog вместо TextField, вы можете создать свой собственный класс, который обеспечит это для вас.Взглянув на исходный код TextInputDialog, вы увидите, что он довольно простой.

То, что я здесь сделал, в основном дублирует этот класс, при этом вместо TextField вместо TextArea:

TextFieldInputDialog.java

import com.sun.javafx.scene.control.skin.resources.ControlResources;
import javafx.application.Platform;
import javafx.beans.NamedArg;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;

/**
 * A dialog that shows a TextArea input
 */
public class TextAreaInputDialog extends Dialog<String> {

    /**************************************************************************
     *
     * Fields
     *
     **************************************************************************/

    private final GridPane grid;
    private final TextArea textArea;
    private final String defaultValue;

    /**************************************************************************
     *
     * Constructors
     *
     **************************************************************************/

    /**
     * Creates a new TextInputDialog without a default value entered into the
     * dialog {@link TextField}.
     */
    public TextAreaInputDialog() {
        this("");
    }

    /**
     * Creates a new TextInputDialog with the default value entered into the
     * dialog {@link TextField}.
     */
    public TextAreaInputDialog(@NamedArg("defaultValue") String defaultValue) {
        final DialogPane dialogPane = getDialogPane();

        // -- textarea
        this.textArea = new TextArea(defaultValue);
        this.textArea.setMaxWidth(Double.MAX_VALUE);
        GridPane.setHgrow(textArea, Priority.ALWAYS);
        GridPane.setFillWidth(textArea, true);

        this.defaultValue = defaultValue;

        this.grid = new GridPane();
        this.grid.setHgap(10);
        this.grid.setMaxWidth(Double.MAX_VALUE);
        this.grid.setAlignment(Pos.CENTER_LEFT);

        dialogPane.contentTextProperty().addListener(o -> updateGrid());

        setTitle(ControlResources.getString("Dialog.confirm.title"));
        dialogPane.setHeaderText(ControlResources.getString("Dialog.confirm.header"));
        dialogPane.getStyleClass().add("text-input-dialog");
        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        updateGrid();

        setResultConverter((dialogButton) -> {
            ButtonBar.ButtonData data = dialogButton == null ? null : dialogButton.getButtonData();
            return data == ButtonBar.ButtonData.OK_DONE ? textArea.getText() : null;
        });
    }

    /**************************************************************************
     *
     * Public API
     *
     **************************************************************************/

    /**
     * Returns the {@link TextField} used within this dialog.
     */
    public final TextArea getEditor() {
        return textArea;
    }

    /**
     * Returns the default value that was specified in the constructor.
     */
    public final String getDefaultValue() {
        return defaultValue;
    }

    /**************************************************************************
     *
     * Private Implementation
     *
     **************************************************************************/

    private void updateGrid() {
        grid.getChildren().clear();

        grid.add(textArea, 1, 0);
        getDialogPane().setContent(grid);

        Platform.runLater(() -> textArea.requestFocus());
    }
}

Теперь вы можете просто добавить этот класс в свой проект и использовать его как любой другой TextInputDialog.

Вот простое приложение, которое использует его:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.util.Optional;

public class TextInputPopup extends Application {

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

    @Override
    public void start(Stage primaryStage) {

        // Simple interface
        VBox root = new VBox(5);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);

        // Create a button to launch the input window
        Button button = new Button("Get input");
        button.setOnAction(e -> {

            // Create the new dialog
            TextAreaInputDialog dialog = new TextAreaInputDialog();
            dialog.setHeaderText(null);
            dialog.setGraphic(null);

            // Show the dialog and capture the result.
            Optional result = dialog.showAndWait();

            // If the "Okay" button was clicked, the result will contain our String in the get() method
            if (result.isPresent()) {
                System.out.println(result.get());
            }

        });

        root.getChildren().add(button);

        // Show the Stage
        primaryStage.setWidth(300);
        primaryStage.setHeight(300);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
}

Конечно, есть место для дальнейшей настройки, но, возможно, это приведет вас в правильном направлении.

...