Hello,
i would like to resize a JComboBox in order to fit its content. The way i thought to use is to get the component of all the item and use getPreferredSize():
public static void redimensionnementAuto(JComboBox combo) {
int width = 1, height = 1;
JList jList = new JList();
for (int i = 0; i < combo.getItemCount(); i++) {
Object o = combo.getItemAt(i);
ListCellRenderer lcr = combo.getRenderer();
Component c = lcr.getListCellRendererComponent(jList, o, i,
combo.getSelectedIndex() == i, combo.hasFocus());
Dimension dim = c.getPreferredSize();
width = Math.max(dim.width, width);
height = Math.max(dim.height, height);
}
// bordure
width += 20;
height += 5;
combo.setSize(width, height);
}
passing null as the JList cause a NPE at javax.swing.DefaultListCellRenderer.getListCellRendererComponent(DefaultListCellRenderer.java:80)
i'm not really happy with this way of doing. Is there any better way to achieve the same result?
Michael Rauscher - 22 Jul 2005 09:51 GMT
Nomak schrieb:
> Hello,
>
> i would like to resize a JComboBox in order to fit its content. The way i thought to use is to get the component of all the item and use getPreferredSize():
Use LayoutManagers.
E.g. the following code should produce a JComboBox that is large enough
to display "A long item"...
// JComboBoxTest.java
import javax.swing.*;
public class JComboBoxTest {
public static final void main( String args[] ) {
JComboBox comboBox = new JComboBox(
new String[]{"Short", "A long item"} );
JFrame frame = new JFrame("...");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( comboBox,
java.awt.BorderLayout.NORTH );
frame.pack();
frame.setVisible(true);
}
}
Bye
Michael