For vextorspace who states:
JMenuBar can only be added to JFrames, JDialogs, and JApplets.
This example shows that it is easy to add JMenuBar to a JPanel (or any container for that matter):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MenuBarEg {
private static void createAndShowGui() {
final JFrame frame = new JFrame("MenuBar Exampe");
JMenuItem barItem = new JMenuItem(new AbstractAction("Bar") {
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(frame, "Hello from bar!");
}
});
JMenu fooMenu = new JMenu("Foo");
fooMenu.add(barItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fooMenu);
JPanel menuBarHoldingPanel = new JPanel(new BorderLayout());
menuBarHoldingPanel.add(menuBar, BorderLayout.PAGE_START);
JPanel mainPanel = new JPanel(new GridLayout(0, 1));
// rigid area just as a place-holder
mainPanel.add(Box.createRigidArea(new Dimension(400, 150)));
mainPanel.add(menuBarHoldingPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Not only is this easy to do, there are many cases where this is desirable.