How make JComboBox drop-down width as wide as needed?

There are some situations where you want the JComboBox size need to be kept as is but you want your drop down part as wide as the longest item in the JComboBox.
Here is the solution in which you can have drop down width same as item having largest width.

We need to create subclass of JComboBox to achieve this. I got this solution from Mark McLaren who has given the work around for the bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4618607 , also done some small modifications to get widest width of the item present in the JComboBox.

Here is a code snippet :
public class WiderDropDownCombo extends JComboBox {

private String type;
private boolean layingOut = false;
private int widestLengh = 0;
private boolean wide = false;

public WiderDropDownCombo( Object[] objs ) {
super( objs );
}

public boolean isWide() {
return wide;
}
//Setting the JComboBox wide
public void setWide(boolean wide) {
this.wide = wide;
widestLengh = getWidestItemWidth();

}
public Dimension getSize(){
Dimension dim = super.getSize();
if(!layingOut && isWide())
dim.width = Math.max( widestLengh, dim.width );
return dim;
}

public int getWidestItemWidth()
{

int numOfItems = this.getItemCount();
Font font = this.getFont();
FontMetrics metrics = this.getFontMetrics( font );
int widest = 0;
for ( int i = 0; i < numOfItems; i++ )
{
Object item = this.getItemAt( i );
int lineWidth = metrics.stringWidth( item.toString() );
widest = Math.max( widest, lineWidth );
}

return widest + 5;
}
public void doLayout(){
try{
layingOut = true;
super.doLayout();
}finally{
layingOut = false;
}
}
public String getType() {
return type;
}

public void setType( String t ) {
type = t;
}
public static void main(String[] args){
String title = "Combo Test";
JFrame frame = new JFrame(title);

String[] items = { "I need lot of width to be visible , oh am I visible now" , "I need lot of width to be visible , oh am I visible now"};
WiderDropDownCombo simpleCombo = new WiderDropDownCombo(items);
simpleCombo.setPreferredSize(new Dimension(180,20));
simpleCombo.setWide(true);
JLabel label  = new JLabel("Wider Drop Down Demo");

frame.getContentPane().add(simpleCombo, BorderLayout.NORTH);
frame.getContentPane().add( label, BorderLayout.SOUTH);
int width = 200;
int height = 150;
frame.setSize(width, height);
frame.setVisible(true);

}
}

If we set setWide as false then it will look like this :
                                                                                                           

If we set setWide as true then output will be :
                                                                                       

Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment