简体   繁体   中英

Aligning JMenu on the right corner of JMenuBar in Java Swing

So if i have a JMenu & JMenuBar defined such that:

jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu1.setText("About");
jMenuBar1.add(jMenu1);

// Finally
setJMenuBar(jMenuBar1);

and with this the Menu "About" is aligned to the left most side of the menu bar. Is there anyway that i can align this menu on the right most side of the menu bar?

There is a patch available for this:

jMenuBar.add(Box.createHorizontalGlue());

Add this line before adding menu to menubar and your menu will come on right side of menubar. Something like:

.....
jMenu1.setText("About");
jMenuBar1.add(Box.createHorizontalGlue()); <-- horizontal glue
jMenuBar1.add(jMenu1);
.....
jMenuBar1.add(Box.createHorizontalGlue());

并且不要忘记将JMenuJMenuItem对齐

JMenu.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 

正如mKorbel对于JMenu所说的那样,它可以像这样在JMenuBar上工作:

    jMenuBar1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

Your may refer to https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html

Especially take a note on part

by putting horizontal glue between two components in a left-to-right box, you make any extra space go between those components

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM