为TextField实现wait-for-enter方法的有效方法? (JavaFX的)

时间:2017-12-15 01:53:22

标签: java javafx eventhandler

我目前正在开发Textadventure,并决定使用scenebuilder将其从控制台移至JavaFX。我使用TextView作为输出,使用TextField作为输入。 这就是我的代码的样子:

public class Story implements Initializable {
    public Button startButton;
    public TextArea textArea;
    public TextField textField;
    public EventHandler mainplot;

    //On startButton pressed
    public void startGame() {
        setEventFilters();
        begin();
    }

    public void begin() {
        print("Welcome to the Adventure."); //print is a method for appending String to textArea
        print("You wake up in your room.");
        print("Fresh air blows through your window.");
        print("You get up. What do you want to do?");
        print("1. Drink from the magical can.");
        print("2. Go outside.");
        textField.addEventFilter(ActionEvent.ACTION, mainplot);
    }

    public void magicalCan() {
        ...
    }

    public void goOutside() {
        ...
    }

    public void setEventFilters() {
        //mainplotFilter
        mainplot = new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e){
                if(textField.getText().equals("1")) {
                    textField.removeEventFilter(ActionEvent.ACTION, mainplot);
                    magicalCan();
                }
                if(textField.getText().equals("2")) {
                    textField.removeEventFilter(ActionEvent.ACTION, mainplot);
                    goOutside();
                }
            }
        };
    }

“守则”继续采用相同的方案 - 更多的事件过滤器用于决策,更多的方法用于故事情节。现在假设我想在故事情节中添加多个enterkey输入:

    public void begin() {
        print("Welcome to the Adventure.");
        //wait for enter to continue
        print("You wake up in your room.");
        print("Fresh air blows through your window.");
        print("You get up. What do you want to do?");
        //wait for enter to continue
        print("1. Drink from the magical can.");
        print("2. Go outside.");
        textField.addEventFilter(ActionEvent.ACTION, mainplot);
    }

实现可以在所有故事情节方法中使用的Eventhandler或waitForEnterkey()方法的最有效方法是什么?

2 个答案:

答案 0 :(得分:1)

以下是您尝试做的一个粗略的例子。这是在提问而不是讲故事,但编程思路非常相似。

Private Sub Save_Click()
On Error GoTo Save_Click_Err

    Me.Today.SetFocus

    On Error Resume Next
    DoCmd.RunCommand acCmdSaveRecord
    If (MacroError <> 0) Then
        Beep
        MsgBox MacroError.Description, vbOKOnly, ""
    End If

    With CurrentDb.OpenRecordset("Data Processing List")
        .AddNew
        !Department = Me.Department.Value
        .Update
    End With

Save_Click_Exit:
    Exit Sub

Save_Click_Err:
    MsgBox Error$
    Resume Save_Click_Exit

End Sub

答案 1 :(得分:0)

添加&#34; ActionListener&#34;到文本字段。当文本字段具有焦点并且用户按 Enter 时,将触发事件。要检索文本,请使用以下代码:

textField.getText();

然后您可以将文本与您正在使用的EventFilter匹配。