Sparsh Parnami
Sparsh Parnami

Reputation: 53

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?

Upvotes: 2

Views: 2784

Answers (4)

subash
subash

Reputation: 3115

simply you put like this

add(menubar,BorderLayout.NORTH);

Upvotes: 1

Mengjun
Mengjun

Reputation: 3197

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.

Upvotes: 2

Dark Knight
Dark Knight

Reputation: 8357

This is what you are looking for

  import javax.swing.*;

import java.awt.GridBagLayout;
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()
{

    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);
    setJMenuBar(menubar);
    file.add(eMenuItem);

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

Upvotes: 0

alex2410
alex2410

Reputation: 10994

You add your menu to container with BorderLayout(it's default) with next code:

add(menubar);

But for adding menu to JFrame you can use next line instead yours.

setJMenuBar(menubar);

output:

enter image description here

Upvotes: 2

Related Questions