Search code examples
javaswingjmenujmenuitemjmenubar

No menu bar display in jmenu bar in java


I have a simple prgram where i want to create a menu bar, menu and menu items. but two problems occur in my program. 1 my frame does not display on center of screen while i have added this code:

mainframe.setLocationRelativeTo(null);

Second problem is that no menu is displaying in frame, however i have added 3-4 menus and menu items inside them

this is my application code:

package javaProject;

import javax.swing.*;


public class Converter {

public static void main(String[] args) 
{

    JFrame mainframe=new JFrame("Converter");
    mainframe.setResizable(true);
    mainframe.setSize(500, 400);
    mainframe.setLocationRelativeTo(null);
    mainframe.setVisible(true);


    JMenuBar menu=new JMenuBar();
    mainframe.setJMenuBar(menu);

    // file menu starts

    JMenu file=new JMenu("File");
    menu.add(file);

    JMenuItem open= new JMenuItem("Open");
    file.add(open);

    JMenuItem save=new JMenuItem("Save");
    file.add(save);

    JMenuItem play=new JMenuItem("Play");
    file.add(play);

    JMenuItem pause=new JMenuItem("Pause");
    file.add(pause);

    JMenuItem exit= new JMenuItem("Exit");
    file.add(exit);

    // edit menu

    JMenu edit= new JMenu("Edit");
    menu.add(edit);

    JMenuItem paste=new JMenuItem("Paste");
    edit.add(paste);


    JMenuItem remove=new JMenuItem("Remove");
    edit.add(remove);

    JMenuItem removeall=new JMenuItem("Remove All");
    edit.add(removeall);

    // convert menu

     JMenu convert=new JMenu ("Convert");
     menu.add(convert);

    // help menu

     JMenu help=new JMenu ("Help");
     menu.add(help);

     JMenuItem supportedformats=new JMenuItem("Supported Formats");
     help.add(supportedformats);

     JMenuItem version=new JMenuItem("Version");
     help.add(version);

    JMenuItem aboutus=new JMenuItem("About Us");
    help.add(aboutus);

    JMenuItem updates=new JMenuItem("Check For Updates");
    help.add(updates);



}

}

Solution

  • Move the code to be after menu initialization

    mainframe.setSize(500, 400);
    mainframe.setLocationRelativeTo(null);
    mainframe.setVisible(true);