I am working on a project using javafx within java8. I focused a weird situation: A panel ( of the class javafx.scene.layout.Pane) containing a button (javafx.scene.control.Button) and another pane. I expect a mouse-clicked event to be bubbled up to the parent. But this is only the case when I click on the pane and does not happen when I click on the button. Below is the code of a very simple example with this behaviour. Does anyone have a suggestion to solve this problem? I know I could create my own button based on a pane.. but this would just be a nasty workaround. Cheers
package application;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
public class Main extends Application {
double curScale;
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
Button btn = new Button("test");
btn.setLayoutX(50);
Pane p2 = new Pane();
p2.setPrefSize(20,20);
p2.setStyle("-fx-background-color: #440000");
Pane p = new Pane();
p.getChildren().add(btn);
p.getChildren().add(p2);
root.setTop(p);
p.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event event) {
System.out.println("event source " + event.getSource() + " target : " + event.getTarget());
}
});
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
By default, the button will consume the mouse click event and the pane will not.
If you want to intercept a button mouse click using a parent pane event handler, then you should use an event filter to do so (to intercept the event during the capturing phase rather than the bubbling phase).
Read up on event processing if you need to understand the capturing versus bubbling concepts.