But it's very simple. Create a window, add a combobox to it. Now shrink the combobox's height, but still have it able to automatically size its width as you add items to itIt's actually not as simple as that. There are a number of different ways of creating a combobox, and a number of different ways of "adding" items to it. I understand why you were not able to create an example, but just saying for the future, it will generally get you an answer faster if you are able to provide something that we can work off.
import java.awt.Dimension;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestComboboxSizing extends JFrame {
public TestComboboxSizing() {
super("Test Combobox Sizing");
setPreferredSize(new Dimension(640, 480));
JPanel panel = new JPanel();
add(panel);
JComboBox comboBox = new JComboBox(new String[] { "Small item", "A very, very, very big item", /*"An even biggggggggggggggggggggggggggggggger item"*/ });
Dimension preferredSize = comboBox.getPreferredSize();
preferredSize.height = 10;
comboBox.setPreferredSize(preferredSize);
panel.add(comboBox);
pack();
}
public static void main(String[] args) {
new TestComboboxSizing().setVisible(true);
}
}
Obviously, lines 19-21 are the main part of the solution. And by changing what items populate the combo box, I was able to confirm that the width does indeed change to fit the longer items, while the height remains constrained.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
protected static JComboBox<String> comboBox = null;
public Test() {
super("Test Combobox Sizing");
setPreferredSize(new Dimension(640, 480));
JPanel panel = new JPanel();
add(panel);
comboBox = new JComboBox<String>();
comboBox.addItem("Small String");
Dimension preferredSize = comboBox.getPreferredSize();
preferredSize.height = 20;
comboBox.setPreferredSize(preferredSize);
JButton btnAdd = new JButton("Test");
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
addNewItem();
}
});
panel.add(comboBox);
panel.add(btnAdd);
pack();
}
public static void main(String[] args) {
new Test().setVisible(true);
}
public static void addNewItem() {
comboBox.addItem("Very very long item entry.");
//TODO: This is where the combobox needs to be resized.
}
}