Search code examples
javaswinglayout-managermenubar

MenuBar appears of the left of the JFrame. how to make it appear on the top of JFrame?


 import javax.swing.*;
import java.awt.event.*;
//import java.awt.event.ActionListener;

 class Test extends JFrame 
 {
    JButton qb=new JButton("quit");
    JPanel p1=new JPanel();
    JMenuBar menubar = new JMenuBar();
   JMenu file = new JMenu("File");
   JMenuItem eMenuItem = new JMenuItem("Exit");
    public Test()
   {
    //setLayout();
    setTitle("this is a test");
    setSize(300,300);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setAlwaysOnTop(true);
    setResizable(true);
    setExtendedState( this.getExtendedState()|JFrame.MAXIMIZED_BOTH );//to set initial state of frame as minimized
    menubar.add(file);
    add(menubar);
    file.add(eMenuItem);

}
public static void main (String[] args) 
{
    new Test();
}

}

i have written the above code and tried to find out the reason of why does the menu bar appears on the left of the frame but failed. also layoutmanager doesnt works in the test constructor. i also tried to insert a button in the code but it didnt appear as well. so what are the poosible reasons of such a behaviour of the frame and what are the solutions?


Solution

  • You can try to call setJMenuBar(..)

    Change you code from

        menubar.add(file);
        add(menubar);
        file.add(eMenuItem);
    

    to

    menubar.add(file);
    file.add(eMenuItem);
    this.setJMenuBar(menubar);
    

    It will work fine then.