gpt4 book ai didi

java - 如何更改 JMenuBar 中 JMenus 的方向

转载 作者:行者123 更新时间:2023-11-29 06:56:52 25 4
gpt4 key购买 nike

当我使用 JMenuBar 在 Java GUI 中创建菜单时它把所有 JMenu s 从左到右的方向是这样的:

enter image description here

我想像这样将其更改为从右到左:

enter image description here

我想在英语操作系统中执行此操作,因此阿拉伯语或从右到左解决方案的建议不是我要找的。

最佳答案

您可以使用 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);
}
}

这看起来像这样:
默认外观(从左到右)
The default left-to-right orientation

切换到从右到左后:
After switching to right-to-left orientation

关于java - 如何更改 JMenuBar 中 JMenus 的方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32817174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com