按下输入键,提交输入并移动到另一个项目

时间:2017-06-11 06:40:06

标签: java javafx keyboard

按下输入键,如何提交输入并移动到另一个项目,例如TextFieldDatePickerButton等?

2 个答案:

答案 0 :(得分:1)

只需使用onAction事件处理程序并在用户提交操作时调用requestFocus(...)来关注下一个控件:

@FXML TextField fName;
@FXML TextField lName;
@FXML DatePicker birthDay;
@FXML TextField address;
@FXML TextField city;
@FXML TextField telephoneNmbr;
@FXML TextField email;
@FXML Button closeBtn;
@FXML Button okBtn;

public void initialize(){

    fName.setOnAction(e -> lName.requestFocus());
    lName.setOnAction(e -> birthDay.requestFocus());
    birthDay.setOnAction(e -> address.requestFocus());

    // etc...

    okBtn.setOnAction(e -> {
        // whatever you need to do when OK is pressed...
    });
}

如果需要,您可以减少代码量:

Control[] focusOrder = new Control[] {
    fName, lName, birthDay, address, city, 
    telephoneNmbr, email, closeBtn, okBtn};

for (int i = 0 ; i < focusOrder-1 ; i++) {
    Control nextControl = focusOrder[i+1];
    focusOrder[i].addEventHandler(ActionEvent.ACTION, e -> nextControl.requestFocus());
}

okBtn.setOnAction(...);

请注意,如果按钮具有键盘焦点,则空格键通常与触发按钮上的操作相关联。您可以将按钮设为&#34;默认按钮&#34;这将改变其外观并使其对输入键做出响应(半全局)。

答案 1 :(得分:0)

我有Stage,其中包含以下内容。我就这样做了:

@FXML TextField fName;
@FXML TextField lName;
@FXML DatePicker birthDay;
@FXML TextField address;
@FXML TextField city;
@FXML TextField telephoneNmbr;
@FXML TextField email;
@FXML Button closeBtn;
@FXML Button okBtn;

public void initialize(){
//ENTER key pressed -> focus on next item
        fName.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:lName.requestFocus();}});
        lName.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:birthDay.requestFocus();}});
        birthDay.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:address.requestFocus();}});
        address.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:city.requestFocus();}});
        city.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:telephoneNmbr.requestFocus();}});
        telephoneNmbr.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:email.requestFocus();}});
        email.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:okBtn.requestFocus();}});

        //ENTER key pressed on okBtn-> Save info
        okBtn.setOnKeyPressed((KeyEvent event) ->{ switch (event.getCode()){
            case ENTER:try {okDugmeKlik(); /*method for saving data into database*/} catch (IOException e) {e.printStackTrace();}}});

}