如何翻转jcombobox?
问题描述:
如何翻转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
为好。
感谢您抽出宝贵时间提供帮助,但只有按钮位于左侧,甚至不会翻转,将组合框留在不良外观中 –
@MichaelShenouda在这种情况下,如果您可以编辑您的问题并澄清问题你的意思是“翻转”。您的问题目前只提到在左侧而不是在右侧放置弹出式菜单按钮。 –
我重新编辑了我的问题,我想你现在要理解我。 –