So I have worked with java Swing for a long time for programming GUI and recently am trying to move to JavaFX. Thus, the question:
I am currently creating a search bar that opens when the user clicks the search button, and then closes when the user clicks off the search bar. In order to detect the click off, I added an EventFilter to the main scene in order to listen for global clicks. I then check the target of the click to see if the click was on components (sorry for the swing terminology) of the search bar, or not. If the click is not in the search bar, close the bar.
primaryStage.getScene().addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
System.out.println(mouseEvent.getTarget());
if(!(mouseEvent.getTarget().equals(searchBarFill) || mouseEvent.getTarget().equals(searchBackground) || mouseEvent.getTarget().equals(searchBarField))){
if(searchBarOpen){
searchBarFill.radiusProperty().unbind();
searchBackground.setDisable(false);
searchBarOpen = false;
Timeline shrink = new Timeline();
Timeline fadeIn = new Timeline();
shrink.setAutoReverse(true);
KeyValue kv = new KeyValue(searchBarFill.radiusProperty(), 0, Interpolator.EASE_BOTH);
KeyFrame kf = new KeyFrame(Duration.millis(250), kv);
KeyValue kv2 = new KeyValue(searchBackground.opacityProperty(), 1.0, Interpolator.EASE_BOTH);
KeyFrame kf2 = new KeyFrame(Duration.millis(100), kv2);
shrink.getKeyFrames().add(kf);
fadeIn.getKeyFrames().add(kf2);
SequentialTransition timeline = new SequentialTransition(shrink, fadeIn);
timeline.play();
}
}
}
});
//This pane holds all search bar Nodes (components)
Pane searchBarPane = new Pane();
searchBarPane.setMaxHeight(50);
headerSearchContainer.getChildren().add(searchBarPane);
If there is a clearly better way of doing this, I would love to know. In programming in swing, I would solve this by checking the target of the mouse press against SwingUtilities.isDescendingFrom(the parent holding on search bar components, the click target). This would let me know whether or not the click was on any of the search bar components.
I have tried to explicitly list out all components in the search bar, but the search bar contains a TextField that registers press targets on the field, the text itself, a random Pane object, and much more nested Nodes i guess?
Is there a similar command in JavaFX, or even a better way of going about this in JavaFX? Thanks