I was wondering if there’s a way to set a ComboBox’ width as wide as the JPanel it’s in.
I have the following code-snippet:
public newPanel() {
setLayout(new GridLayout(2,0));
String[] example = new String[] {"one, "two", "three", "four"};
JComboBox cBox = new JComboBox(levels);
cBox.setPreferredSize(new Dimension(300, 20));
this.add(new JLabel("This is text that goes above the ComboBox:"));
this.add(cBox);
}
You can see that I said that I wanted the ComboBox to be 300px wide, but is there a way to automatically set it as wide as the Panel it’s in?
Something like cBox.setPreferredWidth(max); (I know that doesn’t exist, it’s just to display my way of thinking).
You probably want to let the layout manager take care of this.
If you don’t set the preferred width,
GridLayoutwill make sure the combo box fills the entire panel horizontally.This snippet…
…results in
If this isn’t flexible enough for you, I would recommend you to use a
GridBagLayout.