如果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); } } } 来源:https://www.cnblogs.com/tiankafei/p/10340541.html