user2889419
user2889419

Reputation:

One menu at the right swing-java

Assume I have 5 menus(file, edit, view, window, and help), now I would like to place the help at the right of the frame, and keep the rest at the left, something like this

+----------------------------------------------------------------------------+
| File | Edit | View | Window                                           Help |
+----------------------------------------------------------------------------+

Is it possible with swing? implicitly with menus? or some hack/trick?


Edit/Note:
The help should not be a real Menu object, it would be any clickable object(Jlabel,...)

Upvotes: 1

Views: 272

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

All you need to do is add horizontal glue to the JMenuBar at the location where you want the gap.

menuBar.add(Box.createHorizontalGlue());

e.g.,

import java.awt.Dimension;
import javax.swing.*;

public class MenuEg {

   private static void createAndShowGui() {
      JMenuBar menuBar = new JMenuBar();
      menuBar.add(new JMenu("File"));
      menuBar.add(new JMenu("Edit"));
      menuBar.add(new JMenu("View"));
      menuBar.add(new JMenu("Window"));

      menuBar.add(Box.createHorizontalGlue());
      menuBar.add(new JMenu("Help"));

      JFrame frame = new JFrame("MenuEg");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.setJMenuBar(menuBar);
      frame.getContentPane().add(Box.createRigidArea(new Dimension(600, 400)));
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Upvotes: 4

Related Questions