JavaFX : Menu on a MenuBar disappears instantly on click?

Discussion in 'App Development' started by deanstreet, Jun 14, 2021.

  1. I am trying out a book example on a simple MenuBar.
    The menu bar shows a single File menu, which when clicked should show the individual Open, Close, Save menu items. But as soon as I click on the File menu, those menu items appear in a flash and then disappear in like 1 second. What is going on? Please advise.

    Code:
    import javafx.application.*;
    import javafx.scene.*;
    import javafx.stage.*;
    import javafx.scene.layout.*;
    import javafx.scene.control.*;
    import javafx.event.*;
    import javafx.geometry.*;
       
    public class MenuDemo extends Application {
       
        Label response;
       
        public static void main(String[] args) {
            launch(args);
        }
       
        @Override
        public void start(Stage pStage) {
            pStage.setTitle("Menu Bar Example");
            BorderPane rootNode = new BorderPane();
            Scene myScene = new Scene(rootNode, 300, 300);
            pStage.setScene(myScene);
            response = new Label("fooo");
           
            MenuBar mb = new MenuBar();
           
            Menu fileMenu = new Menu("File");
            MenuItem open = new MenuItem("Open");
            MenuItem close = new MenuItem("Close");
            MenuItem save = new MenuItem("Save");
            MenuItem exit = new MenuItem("Exit");
            //add the items to the menu
            fileMenu.getItems().addAll(open, close, save, exit);
           
            //add the menu to the menu bar
            mb.getMenus().add(fileMenu);
           
           //a handler to display the menuItem clicked on response label
            EventHandler<ActionEvent> menuCall = new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent e) {
                    String itemSelected = ((MenuItem)e.getTarget()).getText();
                    response.setText("The selected item is: " + itemSelected);
                }
            };
           
            open.setOnAction(menuCall);
            close.setOnAction(menuCall);
            save.setOnAction(menuCall);
            exit.setOnAction(menuCall);
           
            rootNode.setTop(mb);
            rootNode.setCenter(response);
           
            pStage.show();
        }   
       
    }
     
  2. It was a problem with the IDE BlueJ..it works when running from the command line
     
  3. it works with netBeans IDE.
     
    deanstreet likes this.