Java FX等待用户输入 [英] Java FX Waiting for User Input

查看:271
本文介绍了Java FX等待用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在JavaFX中编写一个应用程序,并希望创建一个等待用户在我的 TextField 中输入文本并点击的函数在返回(继续)之前输入

  private void setupEventHandlers(){
inputWindow。 setOnKeyPressed(new EventHandler< KeyEvent>(){
@Override
public void handle(KeyEvent e){
if(e.getCode()。equals(KeyCode.ENTER)){
inputWindow.clear();
}
}
});
}

这里我清除 TextField中的文字当用户点击Enter键时。



任何想法?



编辑:我会澄清我正在寻找的东西:

  private void getInput(){
do {
waitForEventToFire();
}
while(!eventFired);
}

显然这只是伪代码,但这正是我要找的。

解决方案

样本解决方案



也许你想要做的是显示一个提示对话框并使用,它将为您处理提示对话框显示。



澄清事件处理程序处理和忙碌等待



您希望:


等待用户输入文本的函数我的TextField并点击输入。


根据定义,这就是 EventHandler 是。
EventHandler在发生此处理程序的类型的特定事件发生时调用。



当事件发生时,您的事件处理程序将触发你可以在事件处理程序中做任何你想做的事情 - 你不需要,并且永远不应该这个事件的忙等待循环。



创建一个TextField操作事件处理程序



不是像你的问题那样在窗口上放置事件处理程序,它可能更好使用 textField.setOnAction

  textField.setOnAction(
new EventHandler< ActionEvent>(){
@Override public void handle(ActionEvent e){
//输入已在文本字段中按下。
//采取任何行动这里需要离子。
}
);

如果将文本字段放在对话框中,并为对话框设置默认按钮,则设置事件文本字段的处理程序是不必要的,因为对话框的默认按钮将拾取并适当地处理回车键事件。


I'm writing an application in JavaFX and would like to create a function that waits for the user to enter text into my TextField and hit Enter before returning (continuing).

private void setupEventHandlers() {
    inputWindow.setOnKeyPressed(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent e) {
            if (e.getCode().equals(KeyCode.ENTER)) {
                inputWindow.clear();
            }
        }
    });
}

Here I clear the text in my TextField when the user hits the Enter key.

Any ideas?

Edit: I'll clarify exactly what I'm looking for:

private void getInput() {
    do {
        waitForEventToFire();
    }
    while (!eventFired);
}

Obviously this is just pseudocode, but this is what I'm looking for.

解决方案

Sample Solution

Perhaps what you want to do is display a prompt dialog and use showAndWait to await for a response from the prompt dialog before continuing. Similar to JavaFX2: Can I pause a background Task / Service?

Likely your situation is a bit simpler than the background task service and (unless you have a long running task involved), you can just do everything on the JavaFX application thread. I created a simple sample solution which just runs everything on the JavaFX application thread

Here is the output of the sample program:

Every time some missing data is encountered, a prompt dialog is shown and awaits user input to fill in the missing data (user provided responses are highlighted in green in the screenshot above).

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;

public class MissingDataDemo extends Application {
  private static final String[] SAMPLE_TEXT = 
    "Lorem ipsum MISSING dolor sit amet MISSING consectetur adipisicing elit sed do eiusmod tempor incididunt MISSING ut labore et dolore magna aliqua"
    .split(" ");

  @Override public void start(Stage primaryStage) {
    VBox textContainer = new VBox(10);
    textContainer.setStyle("-fx-background-color: cornsilk; -fx-padding: 10;");

    primaryStage.setScene(new Scene(textContainer, 300, 600));
    primaryStage.show();

    TextLoader textLoader = new TextLoader(SAMPLE_TEXT, textContainer);
    textLoader.loadText();
  }

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

class TextLoader {
  private final String[] lines;
  private final Pane     container;

  TextLoader(final String[] lines, final Pane container) {
    this.lines = lines;
    this.container = container;
  }

  public void loadText() {
    for (String nextText: lines) {
      final Label nextLabel = new Label();

      if ("MISSING".equals(nextText)) {
        nextLabel.setStyle("-fx-background-color: palegreen;");

        MissingTextPrompt prompt = new MissingTextPrompt(
          container.getScene().getWindow()
        );

        nextText = prompt.getResult();
      }

      nextLabel.setText(nextText);

      container.getChildren().add(nextLabel);
    }              
  }

  class MissingTextPrompt {
    private final String result;

    MissingTextPrompt(Window owner) {
      final Stage dialog = new Stage();

      dialog.setTitle("Enter Missing Text");
      dialog.initOwner(owner);
      dialog.initStyle(StageStyle.UTILITY);
      dialog.initModality(Modality.WINDOW_MODAL);
      dialog.setX(owner.getX() + owner.getWidth());
      dialog.setY(owner.getY());

      final TextField textField = new TextField();
      final Button submitButton = new Button("Submit");
      submitButton.setDefaultButton(true);
      submitButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent t) {
          dialog.close();
        }
      });
      textField.setMinHeight(TextField.USE_PREF_SIZE);

      final VBox layout = new VBox(10);
      layout.setAlignment(Pos.CENTER_RIGHT);
      layout.setStyle("-fx-background-color: azure; -fx-padding: 10;");
      layout.getChildren().setAll(
        textField, 
        submitButton
      );

      dialog.setScene(new Scene(layout));
      dialog.showAndWait();

      result = textField.getText();
    }

    private String getResult() {
      return result;
    }
  }
}

Existing Prompt Dialog Library

There is a pre-written prompt dialog in the ControlsFX library which will handle the prompt dialog display for you.

Clarifying Event Handler Processing and Busy Waiting

You would like:

a function that waits for the user to enter text into my TextField and hit "enter".

By definition, that is what an EventHandler is. An EventHandler is "invoked when a specific event of the type for which this handler is registered happens".

When the event occurs, your event handler will fire and you can do whatever you want in the event handler - you don't need, and should never have a busy wait loop for the event.

Creating a TextField action event handler

Instead of placing the event handler on the window as you have in your question, it is probably better to use a specific action event handler on your text field using textField.setOnAction:

textField.setOnAction(
  new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent e) {
      // enter has been pressed in the text field.
      // take whatever action has been required here.
    }
);

If you place the text field in a dialog with a default button set for the dialog, setting an event handler for the text field is unnecessary as the dialog's default button will pick up and process the enter key event appropriately.

这篇关于Java FX等待用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆