java下拉列表宽度,如何更改JComboBox下拉列表的宽度?

调整 JComboBox 下拉宽度
本文介绍了一种在不改变 JComboBox 宽度的情况下,扩大其下拉列表显示区域的方法。通过自定义 UI 或利用组件内部实现细节,可以实现下拉列表中项目的完整显示,解决了因下拉列表宽度受限而导致内容无法完全展示的问题。

I have an editable JComboBox which contains a list of single letter values. Because of that the combobox is very small.

Every letter has a special meaning which sometimes isn't clear to the user in case of rarely used letters. Because of that I've created a custom ListCellRenderer which shows the meaning of each letter in the dropdown list.

Unfortunately this explanation doesn't fit into the dropdown because it is to small, because it has the same width as the combobox.

Is there any way to make the dropdown list wider than the combobox?

This is what I want to achieve:

---------------------

| Small JCombobox | V |

--------------------------------------------

| "Long item 1" |

--------------------------------------------

| "Long item 2" |

--------------------------------------------

| "Long item 3" |

--------------------------------------------

I cannot change the width of the combobox because the application is a recreation of an old legacy application where some things have to be exactly as they were before. (In this case the combobox has to keep it's small size at all costs)

解决方案

I believe the only way to do this with the public API is to write a custom UI (there are two bugs dealing with this).

If you just want something quick-and-dirty, I found this way to use implementation details to do it (here):

public void popupMenuWillBecomeVisible(PopupMenuEvent e) {

JComboBox box = (JComboBox) e.getSource();

Object comp = box.getUI().getAccessibleChild(box, 0);

if (!(comp instanceof JPopupMenu)) return;

JComponent scrollPane = (JComponent) ((JPopupMenu) comp).getComponent(0);

Dimension size = new Dimension();

size.width = box.getPreferredSize().width;

size.height = scrollPane.getPreferredSize().height;

scrollPane.setPreferredSize(size);

// following line for Tiger

// scrollPane.setMaximumSize(size);

}

Put this in a PopupMenuListener and it might work for you.

Or you could use the code from the first linked bug:

class StyledComboBoxUI extends BasicComboBoxUI {

protected ComboPopup createPopup() {

BasicComboPopup popup = new BasicComboPopup(comboBox) {

@Override

protected Rectangle computePopupBounds(int px,int py,int pw,int ph) {

return super.computePopupBounds(

px,py,Math.max(comboBox.getPreferredSize().width,pw),ph

);

}

};

popup.getAccessibleContext().setAccessibleParent(comboBox);

return popup;

}

}

class StyledComboBox extends JComboBox {

public StyledComboBox() {

setUI(new StyledComboBoxUI());

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值