How do I change the direction of JMenus in a JMenuBar

℡╲_俬逩灬. 提交于 2019-12-24 14:57:36

问题


When I create a menu in java GUI by using JMenuBar it puts all JMenus from Left-to-right direction like this:

I want to change it to Right-to-left like this:

I want do this in an English OS, so suggestions of an Arabic or Right-to-Left solution aren't what I'm looking for.


回答1:


You can use Component.applyComponentOrientation to change the orientation of the JMenuBar:

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

public class R_L_MenuBar_Demo
{
    public static void main(String[] args){
        SwingUtilities.invokeLater(() -> createAndShowGUI());       
    }

    private static void createAndShowGUI()
    {
        JMenuBar mb = new JMenuBar();

        JMenuItem item_1 = new JMenuItem("First Item");
        JMenu menu_2 = new JMenu("Second Menu");
        JMenuItem item_3 = new JMenuItem("First Item in Second");

        menu_2.add(item_3);
        mb.add(item_1);
        mb.add(menu_2);

        //switch the orientation of the menubar to right to left
        JButton btn_r_to_l = new JButton("Switch menubar to r_to_l");
        btn_r_to_l.addActionListener(e -> {
            mb.invalidate();
            mb.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
            mb.validate();
        });

        //switch the orientation of the menubar to left to right
        JButton btn_l_to_r = new JButton("Switch menubar to l_to_r");
            btn_l_to_r.addActionListener(e -> {
            mb.invalidate();
            mb.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            mb.validate();
        });

        JFrame frame = new JFrame("R_L_MenuBar");
        frame.setLayout(new FlowLayout());
        frame.add(btn_r_to_l);
        frame.add(btn_l_to_r);
        frame.setJMenuBar(mb);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200 , 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
   }
}

This will look like this:
The Default look (left to right)

And after switching to right-to-left:



来源:https://stackoverflow.com/questions/32817174/how-do-i-change-the-direction-of-jmenus-in-a-jmenubar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!