java - Handle mouse event anywhere with JavaFX -
i have javafx application, , add event handler mouse click anywhere within scene. following approach works ok, not in way want to. here sample illustrate problem:
public void start(stage primarystage) { root = new anchorpane(); scene = new scene(root,500,200); scene.setonmousepressed(new eventhandler<mouseevent>() { @override public void handle(mouseevent event) { system.out.println("mouse click detected! "+event.getsource()); } }); button button = new button("click here"); root.getchildren().add(button); primarystage.setscene(scene); primarystage.show(); }
if click anywhere in empty space, eventhandler
invokes handle()
method, if click button
, handle()
method not invoked. there many buttons , other interactive elements in application, need approach catch clicks on elements without having manually add new handler every single element.
you can add event filter scene addeventfilter(). called before event consumed child controls. here's code event filter looks like.
scene.addeventfilter(mouseevent.mouse_pressed, new eventhandler<mouseevent>() { @override public void handle(mouseevent mouseevent) { system.out.println("mouse click detected! " + mouseevent.getsource()); } });
Comments
Post a Comment