Java Swing How to - Create right align menu








Question

We would like to know how to create right align menu.

Answer

import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
/*w w w . ja v a 2  s.c o m*/
public class Main {
  public JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(createMenu("Menu 1"));
    menuBar.add(createMenu("Menu 2"));
    menuBar.add(Box.createHorizontalGlue());
    menuBar.add(createMenu("Menu 3"));
    return menuBar;
  }

  public JMenu createMenu(String title) {
    JMenu m = new JMenu(title);
    m.add("Menu item #1 in " + title);
    m.add("Menu item #2 in " + title);
    m.add("Menu item #3 in " + title);
    return m;
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Main demo = new Main();
    frame.setContentPane(demo.createMenuBar());

    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}