简体   繁体   中英

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?

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:

在此处输入图片说明

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.

只是你这样放

add(menubar,BorderLayout.NORTH);

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();
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM