jcomboBox显示长项目的内容

如果JComboBox列表中的内容过长的话,下拉框中不全部显示
解决方法一:当鼠标放在这个过长的项目中时显示tooltip,提示用户选择这项的全部信息
setComboBoxUI(combobox);

private void setComboBoxUI(final JComboBox combobox) {
combobox.setUI(new WindowsComboBoxUI() {
protected ComboPopup createPopup() {
return new BasicComboPopup(combobox) {
protected JList createList() {
return new JList(comboBox.getModel()) {
public void processMouseEvent(MouseEvent e) {
if (e.isControlDown()) {
e = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(),
e.getModifiers() ^ InputEvent.CTRL_MASK, e.getX(), e.getY(),
e.getClickCount(), e.isPopupTrigger());
}
super.processMouseEvent(e);
}

public String getToolTipText(MouseEvent event) {
int index = locationToIndex(event.getPoint());
if (index != -1) {
Object value = getModel().getElementAt(index);
ListCellRenderer renderer = getCellRenderer();
Component rendererComp =
renderer.getListCellRendererComponent(this, value, index, true, false);
if (rendererComp.getPreferredSize().width > getVisibleRect().width) {
return value == null ? null : value.toString();
} else {
return null;
}
}
return null;
}

public Point getToolTipLocation(MouseEvent event) {
int index = locationToIndex(event.getPoint());
if (index != -1) {
Rectangle cellBounds = getCellBounds(index, index);
return new Point(cellBounds.x, cellBounds.y);
}
return null;
}
};
}
};
}
});
}


解决方法二:获取最大长项目宽度,并设置为弹出下拉框时的宽度
combobox.setUI(new LargerComboBoxUI());

class LargerComboBoxUI extends BasicComboBoxUI {
protected ComboPopup createPopup() {
return new LargerComboPopup(comboBox);
}

public class LargerComboPopup extends BasicComboPopup {
public LargerComboPopup(JComboBox comboBox) {
super(comboBox);
}

public void show() {
int selectedIndex = comboBox.getSelectedIndex();
if (selectedIndex == -1) {
list.clearSelection();
} else {
list.setSelectedIndex(selectedIndex);
list.ensureIndexIsVisible(selectedIndex);
}

Insets insets = getInsets();
Dimension listDim = list.getPreferredSize();
boolean hasScrollBar = scroller.getViewport().getViewSize().height != listDim.height;
if (hasScrollBar) {
JScrollBar scrollBar = scroller.getVerticalScrollBar();
listDim.width += scrollBar.getPreferredSize().getWidth();
}

int width = Math.max(listDim.width, comboBox.getWidth() - (insets.right + insets.left));
int height = getPopupHeightForRowCount(comboBox.getMaximumRowCount());
Rectangle popupBounds = computePopupBounds(0, comboBox.getHeight(), width, height);

Dimension scrollSize = popupBounds.getSize();
scroller.setMaximumSize(scrollSize);
scroller.setPreferredSize(scrollSize);
scroller.setMinimumSize(scrollSize);

list.revalidate();
show(comboBox, popupBounds.x, popupBounds.y);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值