如何翻转jcombobox?

问题描述 投票:0回答:1

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

我试过了:

setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

但结果如下:

enter image description here

java jcombobox
1个回答
1
投票

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

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

enter image description here

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

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

© www.soinside.com 2019 - 2024. All rights reserved.