何が起こるかというと、コンボの内部は動的に好ましいサイズを見つけようとします。そのために、リスト内のすべてのアイテムをループし、レンダラーにアイテムをフィードして、レンダリングコンポーネントの推奨サイズを測定します。
測定用のprototypeValueを設定することでそれを防ぐことができ、サイズはそのプロトタイプを使用して一度測定されます
comboBox.setPrototypeDisplayValue(sampleFont);
編集:@Boroが検出したように、それだけでは不十分です-ポップアップのリストではなく、コンボボックス自体のプロトタイプを設定します(当然のことながら、それはどれほど狂ったようにバグがある可能性があります...)。ハックするには、手動で設定する必要があります。これが、遊ぶためのコードスニペットです。
public class ComboWithPrototype {
private JComponent createContent() {
final Font[] systemFonts = GraphicsEnvironment
.getLocalGraphicsEnvironment().getAllFonts();
final JComboBox box = new JComboBox();
box.setRenderer(new ComboBoxRenderer());
box.setPrototypeDisplayValue(systemFonts[0]);
Accessible a = box.getUI().getAccessibleChild(box, 0);
if (a instanceof javax.swing.plaf.basic.ComboPopup) {
JList popupList = ((javax.swing.plaf.basic.ComboPopup) a).getList();
// route the comboBox' prototype to the list
// should happen in BasicComboxBoxUI
popupList.setPrototypeCellValue(box.getPrototypeDisplayValue());
}
Action action = new AbstractAction("set model") {
@Override
public void actionPerformed(ActionEvent e) {
box.setModel(new DefaultComboBoxModel(systemFonts));
}
};
JComponent panel = new JPanel(new BorderLayout());
panel.add(box);
panel.add(new JButton(action), BorderLayout.SOUTH);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ComboWithPrototype().createContent());
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
カスタムListCellRenderer(フォントタイプのアイテムを期待するために少し変更されました)
private class ComboBoxRenderer extends DefaultListCellRenderer {
private Font baseFont = new JLabel("Test").getFont();
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (value instanceof Font) {
Font font = (Font) value;
setFont(new Font(font.getName(), baseFont.getStyle(), baseFont.getSize()));
setText(font.getName());
}
return this;
}
}