dcsimg
Set width of a JComboBox's popup menu?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   chad_moore
Posted On:   Thursday, August 22, 2002 10:48 AM

Is it possible to make a JComboBox have a popup that is wider than the text field? And if so, how?

Re: Set width of a JComboBox's popup menu?

Posted By:   Ajit_Srivastava  
Posted On:   Thursday, August 22, 2002 09:09 PM

Hi,



Please try the sample code below.


You can chose your WidthScaleFactor in the show method of MyComboPopup.

This is mostly a replication of code from swing code base. But this is what I could think of.


Hope it's helpful


Ajit


import javax.swing.*;
import javax.swing.plaf.basic.*;
import java.util.*;
import java.awt.*;

public class ComboTest
{
JPanel m_panel =new JPanel();
JComboBox m_combo;
JFrame m_frame=new JFrame("combo Width Test");

public ComboTest()
{
Vector aVector=new Vector();
aVector.addElement("1");
aVector.addElement("2");
aVector.addElement("3");
aVector.addElement("4");

m_combo=new JComboBox(aVector);
m_combo.setUI(new MyComboUI());

m_panel.add(m_combo);
m_frame.getContentPane().add(m_panel);
m_frame.setSize(300,300);
m_frame.show();
}

public static void main(String [] args)
{
new ComboTest();
}

private class MyComboUI extends BasicComboBoxUI
{
protected ComboPopup createPopup()
{
MyComboPopup popup = new MyComboPopup( comboBox );
popup.getAccessibleContext().setAccessibleParent(comboBox);
return popup;
}
}

private class MyComboPopup extends BasicComboPopup
{
public MyComboPopup(JComboBox combo)
{
super(combo);
}

public void show()
{
int widthScaleFactor=5;
Dimension popupSize = comboBox.getSize();
popupSize.setSize( popupSize.width*widthScaleFactor, getPopupHeightForRowCount( comboBox.getMaximumRowCount() ) );
Rectangle popupBounds = computePopupBounds( 0, comboBox.getBounds().height,
popupSize.width, popupSize.height);
scroller.setMaximumSize( popupBounds.getSize() );
scroller.setPreferredSize( popupBounds.getSize() );
scroller.setMinimumSize( popupBounds.getSize() );
list.invalidate();
syncListSelectionWithComboBoxSelection();
list.ensureIndexIsVisible( list.getSelectedIndex() );

setLightWeightPopupEnabled( comboBox.isLightWeightPopupEnabled() );

show( comboBox, popupBounds.x, popupBounds.y );
}

protected void syncListSelectionWithComboBoxSelection()
{
int selectedIndex = comboBox.getSelectedIndex();

if ( selectedIndex == -1 )
{
list.clearSelection();
}
else
{
list.setSelectedIndex( selectedIndex );
}
}
}
}
About | Sitemap | Contact