I have created a VBox in javafx that comes like a pop up on my application based on hot key combination alt + j. Now all I want to do is close the VBox when I release the key combination alt + j. This is my piece of code
final Stage dialog = new Stage();
EventHandler handler = new EventHandler<KeyEvent>()
{
public void handle( KeyEvent event )
{
if ( event.isAltDown() && event.getCode() == KeyCode.J )
{
dialog.initStyle( StageStyle.UNDECORATED );
// dialog.initModality(Modality.APPLICATION_MODAL);
VBox dialogVbox = new VBox( 25 );
dialogVbox.getChildren().add( new Text( "ABC" ) );
Scene dialogScene = new Scene( dialogVbox, 300, 200 );
dialog.setScene( dialogScene );
dialog.show();
}
else if ( KeyEvent.KEY_RELEASED.equals( eventRel.isAltDown() && eventRel.getCode() == KeyCode.J ) )
{
dialog.hide();
}
}
};
scene.addEventHandler( KeyEvent.KEY_PRESSED, handler );
But this does not close as expected. Please guide me with the VBox close on key release
As per the comment I also created a separate handler for key release : That did not close the vBox
EventHandler handlerRel = new EventHandler<KeyEvent>() {
public void handle(KeyEvent eventRel) {
//event.consume();
if(KeyEvent.KEY_RELEASED.equals(eventRel.isAltDown() && eventRel.getCode() == KeyCode.J))
{
System.out.println("Inside released");
dialog.hide();
}
}};
scene.addEventHandler(KeyEvent.KEY_RELEASED, handlerRel);
Thanks
You are attaching the two handlers to the same scene. However, once the 2nd scene is created, namely dialogScene, it becomes active and is the scene that is receiving events. Therefore, the fix for your solution is to attach the KEY_RELEASED event handler to dialogScene and not the original scene.