1

I have such JPanel:

container = new JPanel();
container.setLayout(new GridLayout(1, 1));

In this panel, I put JLabel and JTextField to create classical form. It renders like this:

image description

Obviously, I'd prefer to have the first column shorter, specifically just as wide as necessary to fit all JLabels. Like this (mspaint figure):

image description

The gray dashed line indicates where the two columns are divided. What do you propose for this layout?

Note that the second column may also contain check box, select box or some other form element.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

1 Answers1

1

Instead of equal width, could elements in my GridLayout take only as much space as needed?

No, it is designed to give elements equal width (and height). If the UI needs different widths, use another layout like GroupLayout or GridBagLayout.

See this answer for an MCVE of doing it using GroupLayout.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • From the image and the code it doesn't seem like introducing different widths for both columns - so it doesn't seem to do what I need. Also, everytime I tried to use GridBaglayout everything went broken, so I avoid it. – Tomáš Zato Mar 01 '15 at 12:14
  • *"From the image and the code.."* Did you actually try swapping the long fields for all short fields?!? *"..everytime I tried to use GridBaglayout everything went broken.."* GBL can be tricky to use, but we sure can't help you debug code we cannot see. Post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) like the code I linked to. – Andrew Thompson Mar 01 '15 at 12:37