如何在JMenuBar中更改JMenus的方向

1 java swing jmenubar jmenuitem jmenu

当我在java GUI中使用JMenuBar它创建一个菜单时,JMenu从左到右的方向放置所有s,如下所示:

在此输入图像描述

我想将它改为从右到左,如下所示:

在此输入图像描述

我想在英语操作系统中这样做,所以阿拉伯语或从右到左解决方案的建议不是我想要的.

Pau*_*aul 6

您可以使用Component.applyComponentOrientation更改以下内容的方向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);
   }
}
Run Code Online (Sandbox Code Playgroud)

这将如下所示:
默认外观(从左到右)
默认的从左到右的方向

在切换到从右到左之后:
切换到从右到左的方向