Search code examples
javafxjavafx-2menuitem

How an action can be performed when clicking on a menu item?


I am doing a project in javafx using Netbeans IDE. I am new to javafx. I have a menu bar in my project. I need to open a new page on the same windows when clicked on each menu item(not new scene). The code is given below :

private VBox addVBox1() {

    final VBox vbox = new VBox();
    vbox.setPadding(new Insets(20,40,30,4)); 
    vbox.setSpacing(10);

    MenuBar menuBar = new MenuBar();

    Menu menuFile1 = new Menu("ADD");
    Menu menuFile2 = new Menu("EDIT");
    Menu menuFile3 = new Menu("VIEW");
    Menu menuFile4 = new Menu("HELP");

    MenuItem add1 = new MenuItem("ENTER STUDENT DETAILS");
    MenuItem add2 = new MenuItem("ENTER C-MARK");
    MenuItem add3 = new MenuItem("ENTER ATTENDANCE");

    MenuItem add4 = new MenuItem("EDIT STUDENT DETAILS");
    MenuItem add6 = new MenuItem("EDIT C-MARK");
    MenuItem add8 = new MenuItem("EDIT ATTENDANCE");

    MenuItem add10 = new MenuItem("STUDENT DETAILS");
    MenuItem add11 = new MenuItem("C-MARK");
    MenuItem add12 = new MenuItem("ATTENDANCE");

    MenuItem add13 = new MenuItem("VIEW HELP"); 

    add1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            //...WHAT TO INCLUDE HERE ?
        }
    });

    menuFile1.getItems().addAll(add1,add2,add3);
    menuFile2.getItems().addAll(add4,add6,add8);
    menuFile3.getItems().addAll(add10,add11,add12);
    menuFile4.getItems().addAll(add13);
    menuBar.getMenus().addAll(menuFile1,menuFile2,menuFile3,menuFile4);

    vbox.getChildren().addAll(menuBar);

    return vbox;
   }

In my project, I open new pages when clicking on buttons. Its code is:

btn2.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent e) {
    ((Stage)btn2.getScene().getWindow()).setScene(new Scene(new Login()));
     }
    });

Is it possible to implement this code in case of menu item ? How should I edit this code to perform an action when clicked on a menu item ?


Solution

  • I don't know exactly what you mean by a new page. There is a Pagination control, but I don't think you mean that. Here's how to add a TextArea but you have to design the UI and choose your own controls.

    add1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            vbox.getChildren().add(new TextArea());
        }
    });
    

    This is how to make a new window but you may want to ask a question about designing dialog boxes. Here's a SO answer https://stackoverflow.com/a/14168238/2855515

    add1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            Stage stage = new Stage();
            Scene scene = new Scene(new VBox());
            stage.setTitle("popup");
            stage.setScene(scene);
            stage.show();
        }
    });