コンボボックスの表示幅が狭い場合に、ポップアップの文字が切れないようにする。
PopupMenuListener インターフェースを継承してクラス を作成し、addPopupMenuListenerに追加する。
public class ExtendPopupMenuListener implements PopupMenuListener {
private boolean isExtend = false;
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
JComboBox combo = (JComboBox) e.getSource();
Dimension size = combo.getSize();
if (!isExtend) {
ListCellRenderer renderer = combo.getRenderer();
JList list = new JList();
list.setFont(combo.getFont());
int width = combo.getWidth();
int itemCount = combo.getItemCount();
for (int index = 0; index < itemCount; index++) {
Object value = combo.getItemAt(index);
Component comp = renderer.getListCellRendererComponent(
list, value, index, false, false);
if (comp != null) {
int w = comp.getPreferredSize().width + 6;
if (width < w) {
width = w;
}
}
}
isExtend = true;
combo.setSize(width, size.height);
combo.showPopup();
}
combo.setSize(size);
isExtend = false;
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
public void popupMenuCanceled(PopupMenuEvent e) {
}
}