0

I have a simple panel with a comboBox, but I'm having a problem with the comboBox, taking up too much space, I can't seem to resize it.

I have the code:

frame.setLayout(new GridLayout(10, 1));
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JLabel("Type:    "));
JComboBox comboBox1 = new JComboBox(labels);
panel.add(comboBox1);

frame.add(panel);

frame.setSize(550,300);
frame.setVisible(true);

Where labels is an array of strings, this is how my comboBox looks after running:

If I try to change the size of the comboBox using setSize(), it doesn't seem to do anything? As I still get the same sized comboBox. Any ideas?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
TTEd
  • 309
  • 1
  • 10

1 Answers1

3

Maybe use a GridBagLayout, which gives you a little more control over the layout, something like...

GridBagLayout

JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Type: "));
panel.add(new JComboBox(new String[]{"This is a test"}));

or if you want the components to be aligned to the left, maybe something like...

Aligned

JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Type: "));
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
panel.add(new JComboBox(new String[]{"This is a test"}), gbc);

See How to Use GridBagLayout for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Hmm, but I wouldn't be able to position it to the far left? And what if I wanted to place things below it, of a type, and combobox, as well. – TTEd Dec 02 '15 at 03:38
  • Yes, see update. Yes, you can supply different constraints, including the `gridx`/`gridy` positions of the components. `GridBagLayout` is among the most flexible of the layout managers, see the linked tutorial for more details – MadProgrammer Dec 02 '15 at 03:40
  • Hmm, do textfields + labels not work with this layout? Something like panel.add(t,gbc); where t is a JTextArea, which only seems to print the label infront of it, i.e "Type". But I get no viewable textArea as output. – TTEd Dec 02 '15 at 03:47
  • Yes, it does work, very well, with mixed controls. You may need to specify the `gridx`/`gridy` positions of your controls though – MadProgrammer Dec 02 '15 at 03:50
  • [For example](http://stackoverflow.com/questions/13437865/java-scroll-to-specific-text-inside-jtextarea/13438455#13438455) – MadProgrammer Dec 02 '15 at 03:52
  • Ahh sorry seems the TextArea was viewable, but only once I maximixed the Window, my bad. Thanks anyway – TTEd Dec 02 '15 at 03:53