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).
is there a way to automatically set it as wide as the Panel it's in?
You probably want to let the layout manager take care of this.
If you don't set the preferred width, GridLayout
will make sure the combo box fills the entire panel horizontally.
This snippet...
import java.awt.GridLayout;
import javax.swing.*;
class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,0));
String[] example = new String[] {"one", "two", "three", "four"};
JComboBox cBox = new JComboBox(example);
//cBox.setPreferredSize(new Dimension(300, 20));
panel.add(new JLabel("This is text that goes above the ComboBox:"));
panel.add(cBox);
panel.setBorder(BorderFactory.createTitledBorder("Panel border"));
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
...results in
If this isn't flexible enough for you, I would recommend you to use a GridBagLayout
.