I am newbie on javafx. I want to show popup menu on Right Mouse click. I find one tutorial Here and Here but don't understand. I want to create popup menu which show in image on this link.
Right now i am creating stage but i don't want stage. I need to show popup menu which show on right click and close when i click anywhere.
Here is my code in which i am using stage but i need to ope popup menu like above link.
public void MouseClickedOnTree(MouseEvent event) {
if (event.isSecondaryButtonDown()) {
System.out.println("secondary press");
final Stage optionstage = new Stage();
VBox vBox = new VBox(5);
vBox.setMinHeight(50);
vBox.setMinWidth(50);
Button btnNewTestBed = new Button("New Testbed");
btnNewTestBed.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
optionstage.close();
stage.show();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
});
Button btnOpenTestbed = new Button("Open Testbed");
btnOpenTestbed.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
optionstage.close();
}
});
optionstage.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ESCAPE) {
System.out.println("click on escape");
//Stage sb = (Stage) label.getScene().getWindow();//use any one object
if(optionstage.isShowing())
optionstage.close();
}
}
});
vBox.getChildren().addAll(btnNewTestBed, btnOpenTestbed);
optionstage.setScene(new Scene(vBox, 100, 100));
//stage.setScene(new Scene(new Group(new Text(50,50, "my second window"))));
optionstage.setX(event.getSceneX());
optionstage.setY(event.getScreenY());
optionstage.initStyle(StageStyle.UNDECORATED);
optionstage.show();
}
Please provide me any link or reference.
The context of your code is not very clear: is this inside an event handler? If so, what's it an event handler for? If not, what is
event
in the openingif
statement?The two links you provide are pretty complex; in JavaFX (unlike Swing) you should only consider subclassing existing Node classes for pretty advanced use cases. You don't need this level of complexity just to create a popup menu.
The easiest way to create a popup menu is for a
Control
(or subclass); you just need to create aContextMenu
, addMenuItem
s to it, and set it as thecontextMenu
on your control:If you want to use a
ContextMenu
on a Node that is not aControl
(aPane
or aShape
, for example), you don't have asetContextMenu(...)
method, so you just need a little more work:See the Javadocs for
ContextMenu
or the tutorial for more details.