Senthil
Senthil

Reputation: 131

How to handle two different enter event in javafx?

I have Pane and text field. I handled enter event using event handler in both Pane and text field. I have written set of codes to perform when Pane enter pressed and text field enter event also. How to stop one event when another event is processing ? (Note: My TextField is in Pane).

    capturePane.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if(event.getCode()==KeyCode.ENTER){
                System.out.println("capture pane enter clicked");
            }
        }
    });

    textFiled.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if(event.getCode()==KeyCode.ENTER){
                System.out.println("text field enter clicked");
            }
        }
    });

In my case both print function worked at a time. I have to perform only one operation. How to do this ? Thanks in advance.

Upvotes: 0

Views: 170

Answers (1)

Matt
Matt

Reputation: 3187

You could do something like this if you are just trying to ignore the first input from the pane but still want to see the capture in the text field. The first one to see the input is the parent node then it continues down which is why you are seeing both print lines when you click enter

public class Main extends Application {

    @Override
    public void start(Stage stage) {
        TextField textField = new TextField();
        textField.addEventFilter(KeyEvent.KEY_RELEASED, event -> {
            if(event.getCode()==KeyCode.ENTER){
                System.out.println("text field enter clicked");
            }
        });

        Pane capturePane = new Pane();
        capturePane.addEventFilter(KeyEvent.KEY_RELEASED, event -> {
            if(event.getTarget()==textField) {
                System.out.println("Caught it and Ignored");
            }
            else if(event.getCode()== KeyCode.ENTER){
                System.out.println("capture pane enter clicked");
                //Do stuff
            }
        });

        capturePane.getChildren().add(textField);

        Scene scene = new Scene(capturePane);
        stage.setScene(scene);
        stage.show();

    }

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

Upvotes: 1

Related Questions