2

I am implmenting a cusom component where the user can type into a TextField and a TableView is pops up then the user can look for items in that table.

I have a problem with the standard KeyEvents of the TextFieldlike Ctrl+A or Home. After the pane with the TableView pops up, those key events are not working anymore. I have checked if the TextField lost the focus but it doesn't, and if I set an EventFilter to see what is happening, it shows that those events are triggered but I see no effect on UI. Even the popup's setHideOnEscape is not working.

Here is a simple code to verify it:

The fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx"
            xmlns:fx="http://javafx.com/fxml"
            fx:controller="textField.Controller">
    <TextField fx:id="textField" prefWidth="400"/>
</AnchorPane>

The controller:

public class Controller implements Initializable {

    @FXML
    private TextField textField;


    @Override
    public void initialize(URL location, ResourceBundle resources) {

        Popup popUp = new Popup();
        TableView<Object> table = new TableView<>();

        table.prefWidthProperty().bind(textField.widthProperty());
        popUp.getContent().add(table);
        popUp.setHideOnEscape(true);
        popUp.setAutoHide(true);


        // To see if the KeyEvent is triggered
        textField.addEventFilter(KeyEvent.ANY, System.out::println);

        textField.setOnKeyTyped(event -> {
            if(!popUp.isShowing()){
                popUp.show(
                        textField.getScene().getWindow(),
                        textField.getScene().getWindow().getX()
                                + textField.localToScene(0, 0).getX()
                                + textField.getScene().getX(),
                        textField.getScene().getWindow().getY()
                                + textField.localToScene(0, 0).getY()
                                + textField.getScene().getY()
                                + textField.getHeight() - 1);
            }
        });
    }
}

And the main:

public class Main extends Application {

    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("View.fxml"));
        AnchorPane pane = loader.load();
        primaryStage.setScene(new Scene(pane, 800, 600));
        primaryStage.show();
    }

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

Here is the console output

KeyEvent [source = TextField[id=textField, styleClass=text-input text-field], target = TextField[id=textField, styleClass=text-input text-field], eventType = KEY_PRESSED, consumed = false, character =  , text = a, code = A]
KeyEvent [source = TextField[id=textField, styleClass=text-input text-field], target = TextField[id=textField, styleClass=text-input text-field], eventType = KEY_TYPED, consumed = false, character = a, text = , code = UNDEFINED]
KeyEvent [source = TextField[id=textField, styleClass=text-input text-field], target = TextField[id=textField, styleClass=text-input text-field], eventType = KEY_RELEASED, consumed = false, character =  , text = a, code = A]
KeyEvent [source = TextField[id=textField, styleClass=text-input text-field], target = TextField[id=textField, styleClass=text-input text-field], eventType = KEY_PRESSED, consumed = false, character =  , text = , code = CONTROL, controlDown, shortcutDown]
KeyEvent [source = TextField[id=textField, styleClass=text-input text-field], target = TextField[id=textField, styleClass=text-input text-field], eventType = KEY_TYPED, consumed = false, character = , text = , code = UNDEFINED, controlDown, shortcutDown]
KeyEvent [source = TextField[id=textField, styleClass=text-input text-field], target = TextField[id=textField, styleClass=text-input text-field], eventType = KEY_RELEASED, consumed = false, character =  , text = a, code = A, controlDown, shortcutDown]
KeyEvent [source = TextField[id=textField, styleClass=text-input text-field], target = TextField[id=textField, styleClass=text-input text-field], eventType = KEY_RELEASED, consumed = false, character =  , text = , code = CONTROL]

Any idea why are those events consumed even if it says they aren't?

Sunflame
  • 2,993
  • 4
  • 24
  • 48
  • _why are those events consumed even if it says they aren't_ actually, they aren't saying it :) The pressed - the type the keyMappings are registered for - never reaches the textfield, so looks like it is consumed by something the event is delivered to before the textfield. Dont know how exactly that happens: my bet would be on the eventDispatcher for the popupWindow. – kleopatra Nov 21 '19 at 13:12
  • 1
    after a bit of debugging: keyEvents are redirected to the focusOwner of the popup's scene (here the table), which consume those that are mapped in its InputMap (f.i. the navigation keys) - which is the end of dispatching of that event. Depending on your requirements, a quick hack might be (or not ;) to set the table's focusTraversable property to false. – kleopatra Nov 21 '19 at 13:53
  • @kleopatra good points, this quick hack works as expected, it lets me use all of the standard TF shortcuts, but it causes another problem which that I want to navigate(with arrows) in the opened table and this makes it a little bit harder, I am working on it to make them working together but if you have any idea with this hack or without I would appreciate it :) – Sunflame Nov 21 '19 at 14:11
  • 1
    guessed so much - than it'll get tricky: the need to not dispatch some keys to the table while not consuming them is kind of contradictory, isn't it :) Maybe a custom eventDispatcher on the table that simply returns events that it finds in a map or so. – kleopatra Nov 21 '19 at 14:19
  • I never implemented a custom eventDispatcher sounds interesting and its a challenge for me, really thank you the suggestions. – Sunflame Nov 21 '19 at 14:23
  • @kleopatra I'm still struggling to implement a custom eventDispatcher, I checked Both: https://stackoverflow.com/questions/51910453/custom-event-dispatcher-javafx and https://stackoverflow.com/questions/51015476/javafx-difference-between-eventdispatcher-and-eventfilter/51015783#51015783 but I still didnt get how to implement a custom one. Maybe can you give me an idea? – Sunflame Nov 25 '19 at 09:34

1 Answers1

1

The reason that the textField doesn't react to some/all "standard function keys" is that their KEY_PRESSED type never reaches it - they are redirected to the table in the popup and most/all of them consumed by the table.

A naive first approximation would be to set the table's focusTraversable property to false: this effectively prevents all keys from being delivered to it. Real-world requirements might be a bit less simplistic, in that some of those should reach the table while others should bubble up to the textField.

This can be achieved by a custom EventDispatcher (on the table) which examines all keyEvents and decides which to deliver/not to the table's original dispatcher. A code snippet where interceptor is a predicate used for the decision (at the end there's complete working example for convenience):

private BasicEventDispatcher original;
private Predicate<Event> interceptor;

@Override
public Event dispatchEvent(Event event, EventDispatchChain tail) {
    if (!interceptor.test(event)) {
        event = original.dispatchCapturingEvent(event);
        if (event.isConsumed()) {
            return null;
        }
    }
    event = tail.dispatchEvent(event);
    if (event != null && !interceptor.test(event)) {
        event = original.dispatchBubblingEvent(event);
        if (event.isConsumed()) {
            return null;
        }
    }
    return event;
}

It's usage: if f.i. we want LEFT and RIGT be bubbled up to that textField, while all others should be handled normally by the table

List<KeyCode> toIntercept = List.of(KeyCode.LEFT, KeyCode.RIGHT);
Predicate<Event> interceptor = e -> {
    if (e instanceof KeyEvent) {
        return toIntercept.contains(((KeyEvent) e).getCode());
    }
    return false;
};
table.setEventDispatcher(new InterceptingEventDispatcher(
        (BasicEventDispatcher) table.getEventDispatcher(), interceptor));

A complete example to play with:

public class ViewPopupApplication extends Application {

    public static class InterceptingEventDispatcher implements EventDispatcher {
        private BasicEventDispatcher original;
        private Predicate<Event> interceptor;

        public InterceptingEventDispatcher(BasicEventDispatcher original, Predicate<Event> interceptor) {
            this.original = original;
            this.interceptor = interceptor;
        }

        @Override
        public Event dispatchEvent(Event event, EventDispatchChain tail) {
            if (!interceptor.test(event)) {
                event = original.dispatchCapturingEvent(event);
                if (event.isConsumed()) {
                    return null;
                }
            }
            event = tail.dispatchEvent(event);
            if (event != null && !interceptor.test(event)) {
                event = original.dispatchBubblingEvent(event);
                if (event.isConsumed()) {
                    return null;
                }
            }
            return event;
        }

    }

    private Parent createContent() {
        TableView<Locale> table = new TableView<>(FXCollections.observableArrayList(Locale.getAvailableLocales()));
        // just to see that right/left are intercepted while up/down are handled
        table.getSelectionModel().setCellSelectionEnabled(true);

        TableColumn<Locale, String> country = new TableColumn<>("Country");
        country.setCellValueFactory(new PropertyValueFactory<>("displayCountry"));
        TableColumn<Locale, String> language = new TableColumn<>("Language");
        language.setCellValueFactory(new PropertyValueFactory<>("displayLanguage"));
        table.getColumns().addAll(country, language);
        // disables default focus traversal
        //  table.setFocusTraversable(false);

        // decide which keys to intercept
        List<KeyCode> toIntercept = List.of(KeyCode.LEFT, KeyCode.RIGHT);
        Predicate<Event> interceptor = e -> {
            if (e instanceof KeyEvent) {
                return toIntercept.contains(((KeyEvent) e).getCode());
            }
            return false;
        };
        table.setEventDispatcher(new InterceptingEventDispatcher(
                (BasicEventDispatcher) table.getEventDispatcher(), interceptor));

        TextField textField = new TextField("something to show");
        textField.setPrefColumnCount(20);
        textField.setText("something to see");

        table.prefWidthProperty().bind(textField.widthProperty());
        Popup popUp = new Popup();
        popUp.getContent().add(table);

        textField.setOnKeyTyped(event -> {
            if(!popUp.isShowing()){
                popUp.show(
                        textField.getScene().getWindow(),
                        textField.getScene().getWindow().getX()
                                + textField.localToScene(0, 0).getX()
                                + textField.getScene().getX(),
                        textField.getScene().getWindow().getY()
                                + textField.localToScene(0, 0).getY()
                                + textField.getScene().getY()
                                + textField.getHeight() - 1);
            }
        });

        BorderPane content = new BorderPane(textField);
        return content;
    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setScene(new Scene(createContent()));
        stage.show();
    }

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

}
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • 1
    Thank you a lot, I couldn't imagine how does it works even if I read those answers written by Slaw, lacking a working example, but this kind of brings me closer to understanding it. Really nice solution, I can use it, and even further develop handling also the shortcuts like if Shift is down etc. – Sunflame Nov 25 '19 at 12:09
  • 1
    glad it helps :) – kleopatra Nov 25 '19 at 12:12