如何翻转 jComboBox
以使弹出菜单按钮位于左侧而不是右侧?
我已经尝试过:
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
但结果是这样的:
最佳答案
下拉箭头的位置由与 JComboBox
关联的 ComboBoxUI
控制。通常,如果您想更改此行为,则必须创建自己的 ComboBoxUI
实现。幸运的是,针对您的特定需求,还有另一种方法。默认的 ComboBoxUI
被编码为默认将箭头放置在右侧,但如果组件方向更改为从右到左,它将把箭头放置在左侧:
JComboBox<String> comboBox = new JComboBox<>(new String[]{"One", "Two", "Three"});
comboBox.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
正如您所看到的,这将影响整个组件的方向,但不会影响组合框中列表框项目的方向。要进行此调整,请在与组件关联的 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);
最后,如果您的组合框是可编辑的,您可能还需要在编辑器组件上使用 applyComponentOrientation
。
关于java - 翻转 jcombobox 怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614915/