A.R.S.D.
A.R.S.D.

Reputation: 300

Event Handler in javaFx for menu

I have a question in JavaFX , how can i set an event Handler for menu (not menu bar or menu item) that when i clicked on the menu a popup window appear. i have tried this but when i click on menu nothing happens:

settingsMenu.addEventHandler(MouseEvent.MOUSE_CLICKED,event -> {//To DO});

and even the code below doesn't works:

settingMenu.setOnAction(event -> {//To Do});

Upvotes: 0

Views: 4765

Answers (1)

SedJ601
SedJ601

Reputation: 13859

Here is a hack. Menu has a constructor Menu(String text, Node graphic). Set the String to empty-string and the Node to Label. Then add a MouseListener to the Label.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @author Sedrick
 */
public class JavaFXApplication33 extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("Help!");
        label.setOnMouseClicked(mouseEvent->{System.out.println("Hello World!");});
        Menu menu = new Menu("", label);
        MenuBar menuBar = new MenuBar();
        menuBar.getMenus().add(menu);


        StackPane root = new StackPane();
        root.getChildren().add(menuBar);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

Upvotes: 1

Related Questions