java - 翻转 jcombobox 怎么样?

标签 java jcombobox

如何翻转 jComboBox 以使弹出菜单按钮位于左侧而不是右侧?

我已经尝试过:

setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

但结果是这样的:

enter image description here

最佳答案

下拉箭头的位置由与 JComboBox 关联的 ComboBoxUI 控制。通常,如果您想更改此行为,则必须创建自己的 ComboBoxUI 实现。幸运的是,针对您的特定需求,还有另一种方法。默认的 ComboBoxUI 被编码为默认将箭头放置在右侧,但如果组件方向更改为从右到左,它将把箭头放置在左侧:

JComboBox<String> comboBox = new JComboBox<>(new String[]{"One", "Two", "Three"});
comboBox.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

enter image description here

正如您所看到的,这将影响整个组件的方向,但不会影响组合框中列表框项目的方向。要进行此调整,请在与组件关联的 ListCellRenderer 上调用 applyComponentOrientation。如果您有自定义渲染器,则只需调用该对象上的方法即可。使用默认渲染器,这有点棘手,但仍然是可能的:

ListCellRenderer<? super String> defaultRenderer = comboBox.getRenderer();
ListCellRenderer<String> modifiedRenderer = new ListCellRenderer<String>() {
    @Override
    public Component getListCellRendererComponent(JList<? extends String> list, String value, int index,
            boolean isSelected, boolean cellHasFocus) {
        Component component = defaultRenderer.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus);
        component.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        return component;
    }
};
comboBox.setRenderer(modifiedRenderer);

enter image description here

最后,如果您的组合框是可编辑的,您可能还需要在编辑器组件上使用 applyComponentOrientation

关于java - 翻转 jcombobox 怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614915/

相关文章:

java - Jmeter POST API问题

java - JSP中的登录验证和 session

java - Android - 锁定所有其他应用程序

java - 如何更改 Eclipse 检查向导窗口的默认大小

java - 如何更改禁用的 JComboBox 上(显示的)所选项目?

java - 使用 jcombobox 在 java 中过滤国家/地区-州-城市代码

Java BufferedReader 文件路径问题

java - 无法使 ListCellRenderer 正常运行

java - 如何在 JTable 中添加 JCombobox 并在 JTable 内触发其操作?

java - 将 JComboBox 中的项目替换为数组