JMenuBar and JPanel

A

Ajay

It seems JMenuBar can be added only to JInternalFrame and thus
appearing only at the North of the frame..

There is also some sample program on the sun site showing how you can
add on the west side.

I was wondering if anyone figured out a way to add it to a JPanel there
by you could add it to any part of the interface..

Thanks,
Ajay.
 
Z

zero

It seems JMenuBar can be added only to JInternalFrame and thus
appearing only at the North of the frame..

There is also some sample program on the sun site showing how you can
add on the west side.

I was wondering if anyone figured out a way to add it to a JPanel
there by you could add it to any part of the interface..

Thanks,
Ajay.


A JMenuBar is a Component, so you can add it to any Container -
including JPanels. The following example looks way ugly, but it should
prove that it is in fact possible to put a JMenuBar just about anywhere
you want. It has a menu bar at the top level on the south of the JFrame
contentpane, and on a separate JPanel. To make it extra clear, this
second menu bar is in the center of the JPanel (which in turn is in the
center of the contentpane). To show where the JPanel is I gave it a red
border.

public class TestJMenuBar extends javax.swing.JFrame
{
public TestJMenuBar()
{
super("TestJMenuBar");

javax.swing.JMenuBar sbar = new javax.swing.JMenuBar();
javax.swing.JMenu smenu = new javax.swing.JMenu("South menu");
javax.swing.JMenuItem item = new javax.swing.JMenuItem("item");
smenu.add(item);
sbar.add(smenu);

javax.swing.JMenuBar cbar = new javax.swing.JMenuBar();
javax.swing.JMenu cmenu = new javax.swing.JMenu("Center menu");
javax.swing.JMenuItem citem = new javax.swing.JMenuItem("item");
cmenu.add(citem);
cbar.add(cmenu);

javax.swing.JPanel panel = new javax.swing.JPanel();
panel.setLayout(new java.awt.BorderLayout());
panel.add(new javax.swing.JLabel("north label in JPanel"),
java.awt.BorderLayout.NORTH);
panel.add(cbar, java.awt.BorderLayout.CENTER);
panel.setBorder(new javax.swing.border.LineBorder(
java.awt.Color.RED));

java.awt.Container pane = getContentPane();
pane.setLayout(new java.awt.BorderLayout());
pane.add(new javax.swing.JLabel("north label"),
java.awt.BorderLayout.NORTH);
pane.add(new javax.swing.JLabel("west label"),
java.awt.BorderLayout.WEST);
pane.add(panel, java.awt.BorderLayout.CENTER);
pane.add(sbar, java.awt.BorderLayout.SOUTH);
}

public static void main(String[] args)
{
TestJMenuBar app = new TestJMenuBar();
app.setSize(300, 300);
app.setDefaultCloseOperation(EXIT_ON_CLOSE);
app.setVisible(true);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top