Aligning a ‘Help’ JMenu component to the right side of the JMenuBar

JMenuBar has a method called setHelpMenu but you’ll get a runtime error when you try to use it. A workaround is to use Box.createHorizontalGlue to create the necessary empty space between the last left-aligned menu and the help menu. For more information about BoxLayout and its static methods, check out the link below.

Main.java:

import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*; 
 
public class Main extends JFrame {
   public Main() {
      JMenu fileMenu = new JMenu("File");
      fileMenu.add(new JMenuItem("Open"));
      fileMenu.add(new JMenuItem("Save"));
 
      JMenu helpMenu = new JMenu("Help");
      helpMenu.add(new JMenuItem("Help Topics"));
      helpMenu.add(new JSeparator());
      helpMenu.add(new JMenuItem("About"));
 
      JMenuBar mb = new JMenuBar();
      mb.add(fileMenu);
      // following line of code gives a runtime exception:
      //        "setHelpMenu() not yet implemented"
      //mb.setHelpMenu(helpMenu);
 
      // workaround:
      mb.add(Box.createHorizontalGlue());
      mb.add(helpMenu);
      
      this.setJMenuBar(mb);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}