Till now, we have seen how to add JMenu to JMenuBar. Now, we'll be applying a simple hack that lets you place JMenu at the center of JMenuBar.
import javax.swing.*;
import java.awt.*;
class CenteredJMenu extends JFrame
{
JMenuBar mb;
JMenu m;
JMenuItem m1,m2;
public CenteredJMenu()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Centered JMenu");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
mb=new JMenuBar();
m=new JMenu("Menu");
m1=new JMenuItem("Item 1");
m2=new JMenuItem("Item 2");
m.add(m1);
m.add(m2);
mb.add(m);
// This does the thing!
mb.setLayout(new GridBagLayout());
setJMenuBar(mb);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new CenteredJMenu();
}
}