如何在JMenuBar中更改JMenus的方向 [英] How do I change the direction of JMenus in a JMenuBar

查看:170
本文介绍了如何在JMenuBar中更改JMenus的方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用JMenuBar在Java GUI中创建菜单时,它会将所有JMenu从左到右放置,如下所示:

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.

推荐答案

您可以使用

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:

这篇关于如何在JMenuBar中更改JMenus的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆