Event with KeyPressed Event to open another window JAVAFX

2

My problem is as follows, this way I'm opening the window I have a problem using the KeyPressed function. So this way my method needs the ActionEvent parameter which when using the getSource () method, returns me the button and open the window correctly, but that's when I click the button. So for the function of the button to work inside the keyPressed function, I would have to put a parameter there as well. I tried putting new ActionEvent and (), the error some though the source is different when I press enter, which causes window n to open.

Below is the example that opens the second window by clicking the button. And lastly the KeyPressed event.

Aah, the idea is a login window, so when I enter enter do the checks and talz and open the other window. But it only works by clicking same

private void openJane (ActionEvent event) throws Exception {

    Parent main_tela = FXMLLoader.load(getClass().getResource("FXMLTelaPrincipal.fxml"));
    Scene main = new Scene(main_tela);
    Stage st = (Stage) ((Node) event.getSource()).getScene().getWindow();
    st.hide();
    st.setScene(main);
    st.show();

}

public void initialize(URL url, ResourceBundle rb) {
    btnLogar.addEventHandler(KeyEvent.KEY_PRESSED, (KeyEvent event) -> {
        try {
            if (event.getCode() == KeyCode.ENTER) {
                abrirJanela();
            }
        } catch (Exception ex) {
        }
    });
    
asked by anonymous 18.09.2017 / 21:41

1 answer

0

JavaFX has an easier way to make a button react to the ENTER event, just put it default button . Basically a button in JavaFX can be of 3 types:

  • Normal: Standard behavior, reacting only with click;
  • Default: A default button is a button that also fires with a keyboard event of type VK_ENTER, as long as no other node in the scene consumes this event;
  • Cancel: A cancel button is a button that also fires with a keyboard event of type VK_ESC, as long as no other node in the scene consumes this event;

See the correct way below:

Button mybutton = new Button();
mybutton.setDefaultButton(true);

mybutton.setOnAction((ActionEvent t) -> {
    // Seu evento
});
    
19.09.2017 / 00:22