Java菜单栏不会出现

时间:2013-04-09 18:02:30

标签: java jmenubar

嘿伙计们,我正在尝试从其他课程中为我的JFrame制作一个菜单栏,但它狡猾地拒绝工作! 我在一个deadend ......

我真的不知道出了什么问题,我尝试了其他一些方法,但它没有用......

The code is this :

  public Engine(int width, int height) {
    System.out.println("TEST ENGINE CLAASS");
    setTitle("Battleship Board - Place Your Ships");
    setSize(width, height);
    setLocation(624, 373);
    setDefaultCloseOperation(3);
    setResizable(false);
    setVisible(true);
    setLayout(null);

    System.out.println("TEST ENGINE clas2");
    Menu menu = new Menu(this);
    super.setJMenuBar(menu.getMenuBar());




    setDefaultCloseOperation(3);
}

并在Menu.class:

public class Menu implements ActionListener {
    private Engine cc;
    private JMenuBar menuBar;
    private JMenu game;
    private JMenu help;
    private JMenuItem aboutItem;
    private JMenuItem quitItem;
    private JMenuItem newGameItem;

    public Menu (Engine cc) {
        System.out.println("testing menu class");
        this.cc = cc;
        this.menuBar = new JMenuBar();
        this.game = new JMenu("Game");
        this.help = new JMenu("Help");

        makeGameMenu();
        makeAboutMenu();


    }



   private void makeGameMenu() {
        System.out.println("Making game menu");
        this.newGameItem = new JMenuItem("New Game");
        this.game.add(this.newGameItem);
        this.newGameItem.addActionListener(this);
        this.game.addSeparator();

        this.quitItem.addActionListener(this);


        this.game.add(this.quitItem);
         this.menuBar.add(this.game);

    }

   private void makeAboutMenu() {
        this.aboutItem = new JMenuItem("About");
        this.help.add(aboutItem);
        this.menuBar.add(this.help);


    }

   public void actionPerformed(ActionEvent event) {
       JMenuItem source = (JMenuItem)event.getSource();

       //If user clicks new game then:
       if (source == this.newGameItem) {
           this.cc.newGame();
       }
       //If user clicks Quit then:
       else if (source == this.quitItem) {
           System.exit(0);
       }
       //If user clicks Help - About then:
       else if (source == this.aboutItem) {
           JOptionPane.showMessageDialog(null, "This Battleship Game was created by Manos Kontakis for Object Oriented Programming Lab", "About", 1);
       }
   }

   public JMenuBar getMenuBar()
  {
    return this.menuBar;
  }


}

2 个答案:

答案 0 :(得分:2)

JMenuItem quitItem尚未在任何地方进行初始化,因此在将JMenuBar添加到JFrame之前会抛出异常:

quitItem = new JMenuItem("Quit Game");
quitItem.addActionListener(...);

除此之外:避免使用绝对定位(null布局)并始终使用布局管理器。

答案 1 :(得分:0)

我认为您必须从JMenuBar扩展并将组件添加到“this”。