The following example places a JComboBox on a Frame and loads 5 items.
When the application runs, the combobox is displayed and what is seen is "Long Item..."
Without knowing actually activating the combobox, the user has no idea which record is actually visible.
Keep in mind, this is actually a dynamically loaded JComboBox. Using hard-coded values only for the example. As a result, the length of the longest string won't be available until run-time.
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class JComboBoxTestLength {
JFrame f;
JComboBoxTestLength (){
f=new JFrame("ComboBox Example");
String country[]={"Long Item 5","Long Item 2","Long Item 1","Long Item 8","Long Item 4"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new JComboBoxTestLength ();
}
}
Some threads indicate to avoid using setPreferredSize().
Although I could just set the setBounds() values to be long enough but want it to look aesthetically pleasing and would like to calculated it based on the longest string + 2 or something like that.
Is it possible to calculate the width for the JComboBox to avoid seeing '...' appear for any of the text?
As commented by Andrew Thomson use Layout managers to achieve the desired layout.
In this case wrapping the combo with a JPanel
that uses FlowLayout
can do the work for you:
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JComboBoxTestLength {
JComboBoxTestLength (){
JFrame f=new JFrame("ComboBox Example");
String country[]={"Long Item 5","Long Item 2","Long Item 1","Long Item 8","Long Item 4"};
JComboBox<String> cb=new JComboBox<>(country);
JPanel comboPane = new JPanel(); //uses FlowLayout by default
comboPane.add(cb);
f.add(cb); //JFrame content pane uses BorderLayout by default
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new JComboBoxTestLength ();
}
}