Question

I'm implementing ENTER as TAB in my JavaFX application, as a requisite of users. I'm using the following code to identify all Control that exists in a Pane and add a OnKeyPressed handler:

protected EventHandler<KeyEvent> processadorEnterEmCampo = new EventHandler<KeyEvent>() {
    public void handle(final KeyEvent evento) {
        if (evento.getCode() == KeyCode.ENTER) {
            evento.consume();
            ((Node)evento.getSource()).fireEvent(new KeyEvent(evento.getSource(), evento.getTarget(), evento.getEventType(), null, "TAB", KeyCode.TAB, false, false, false, false));
        }
    }
};  

private void adicionarProcessadorEventoEnterPressionado(Node elemento) {
    if(elemento instanceof Pane){
        Pane painel= (Pane) elemento;
        for(Node filho :painel.getChildren()){
            if(filho instanceof TextField || filho instanceof ComboBox || filho instanceof CheckBox
                    || filho instanceof DatePicker || filho instanceof BigDecimalField)
                filho.setOnKeyPressed(processadorEnterEmCampo);
            else if(filho instanceof Button)
                filho.setOnKeyPressed(processadorEnterEmBotao);
            else
                adicionarProcessadorEventoEnterPressionado(filho);
        }
    }
}

The above code runs like a charm, except for BigDecimalField and DatePicker. It simply don't runs handler's code when I press ENTER key, only when I press SHIFT key the handler's code is executed. I believe this is happening because these components already have some functionality with ENTER key. What I could do to handle ENTER key press in these components?

Was it helpful?

Solution

Instead of use setOnKeyPressed, now I'm using addEventFilter:

private void adicionarProcessadorEventoEnterPressionado(Node elemento) {
    if(elemento instanceof Pane){
        Pane painel= (Pane) elemento;
        for(Node filho :painel.getChildren()){
            if(filho instanceof TextField || filho instanceof ComboBox || filho instanceof CheckBox
                    || filho instanceof DatePicker || filho instanceof BigDecimalField)
                filho.addEventFilter(KeyEvent.KEY_PRESSED,processadorEnterEmCampo);
            else if(filho instanceof Button)
                filho.setOnKeyPressed(processadorEnterEmBotao);
            else
                adicionarProcessadorEventoEnterPressionado(filho);
        }
    }
}

As I was suspecting that the implementation of the components was consuming the event before it gets to the handler, addEventFilter was the best bet:

The filter is called when the node receives an Event of the specified type during the capturing phase of event delivery.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top