Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to right-align a menu in the menu bar with Java?
Let’s say we added a menu to the MenuBar −
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
Add the glue component in between the menus to align some of them on the right, for example −
menuBar.add(Box.createHorizontalGlue());
The menu added after the usage of above method, would get right-aligned −
JMenu sourceMenu = new JMenu("Source");
sourceMenu.setMnemonic(KeyEvent.VK_S);
menuBar.add(sourceMenu);
The following is an example to right-align a menu in the menu bar with Java −
Example
package my;
import java.awt.event.KeyEvent;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SwingDemo {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuBar Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(menuItem1);
JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O);
fileMenu.add(menuItem2);
JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic(KeyEvent.VK_E); menuBar.add(editMenu);
JMenuItem menuItem3 = new JMenuItem("Cut", KeyEvent.VK_C); editMenu.add(menuItem3);
menuBar.add(Box.createHorizontalGlue());
JMenu sourceMenu = new JMenu("Source");
sourceMenu.setMnemonic(KeyEvent.VK_S);
menuBar.add(sourceMenu);
JMenu refactorMenu = new JMenu("Refactor");
refactorMenu.setMnemonic(KeyEvent.VK_R);
menuBar.add(refactorMenu);
JMenu navigateMenu = new JMenu("Navigate");
navigateMenu.setMnemonic(KeyEvent.VK_A);
menuBar.add(navigateMenu);
menuBar.revalidate();
frame.setJMenuBar(menuBar);
frame.setSize(550, 350);
frame.setVisible(true);
}
}
Output

Advertisements