翻转 jcombobox 怎么样?
How about flipping a jcombobox?
如何翻转 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
。
如何翻转 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
。