Reputation:
Hi I want to Reduce and Expand Size of multiple JComboBox, according to Font type, and its String items. But I can't get the desired results...
I want to fit (no more space or no less spaces needed) the all JComoboBox according the largest String items.
theFont = new Font("Serif",Font.PLAIN, 11);
TheFont is a common Font in Linux and Windows
Sorry I forget to say I working with Netbeans!!! and I executing my code after: initComponents();
List<Component> lTabs = new ArrayList<>();
JPanel jpTab = //Some JPanel;
addComponents(jpTab, lTabs);
for (int ii = 0; ii < lTabs.size(); ii++) {
if (lTabs.get(ii) instanceof javax.swing.JComboBox) {
javax.swing.JComboBox jcb = (javax.swing.JComboBox)lTabs.get(ii);
int posMax = 0;
int MaxSize = 0;
String itemString = "";
// find largest String
for (int k = 0; k < jcb.getItemCount();k++) {
itemString = " "+((String)jcb.getItemAt(k)).trim(); //All String items have Two aditional spaces
if (MaxSize < (fm.stringWidth(itemString))) { //
MaxSize = fm.stringWidth(itemString);
posMax = k;
}
}
// System.out.println("JComboBox "+" Pos->:"+posMax+" Val->:"+jcb.getItemAt(posMax)+" Old->:"+jcb.getWidth()+" New->:"+MaxSize);
jcb.setPreferredSize(new Dimension(MaxSize, jcb.getHeight()));
jcb.setFont(theFont);
jcb.setPrototypeDisplayValue(" "+jcb.getItemAt(posMax));
}
}
public void addComponents(Container c, List<Component> l) {
Component ca[] = c.getComponents();
l.addAll(Arrays.asList(ca));
for (int i = 0; i < ca.length; i++) {
Component component = ca[i];
if (Container.class.isAssignableFrom(component.getClass())) {
addComponents((Container) component, l);
}
}
}
How can I to Fit all JComboBox contained in some JPanel?
PD: I don't want this method: http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough
EDIT 2 ¿Is possible to calculate Width empty items for JComboBox (without Items)?
Upvotes: 0
Views: 199
Reputation: 324197
I want to Reduce and Expand Size of multiple JComboBox, according to Font type, and its String items
This is the default behaviour. The combo box will iterate through all the items to determine the appropriate size.
You don't have to do anything special.
jcb.setPrototypeDisplayValue(" "+jcb.getItemAt(posMax));
Get rid of that statement. That is only used to fix the width using a specific string. The benefit of using this method is that the combo box doesn't need to iterate through all the items in the list, so it can be more efficient.
So basically you have replaced the default iteration to determine the preferred size with a loop of your own. Get rid of your code and just use the default behaviour.
Upvotes: 2