tags:

views:

44

answers:

3

I have a JPanel that I want to use to contain 3 vertical components:

  1. a JLabel
  2. a JTextField
  3. a JScrollPane

I want all 3 components to fill the JPanel's width. I want the JLabel and JTextField to use their normal heights and the JScrollPane to use the rest.

BoxLayout almost works, except it seems like the JTextField and JScrollPane share the "extra" space when the JPanel is made large.

What can I do?

+1  A: 

GridBagLayout is pretty handy. You can control anything you need and you can control only what you need. You're probably going to be interested in only the vertical parameters.

Seth
+2  A: 

Create a BorderLayout. Put the JScrollPane in its center.

Create a JPanel with a BoxLayout. Put the JLabel and JTextField in that, vertically. Put that JPanel into the NORTH side of the BorderLayout.

Jonathan Feinberg
hurray for simplicity! thanks!
Jason S
A: 

You could also use DesignGridLayout as follows:

DesignGridLayout layout = new DesignGridLayout(thePanel);
layout.row().center().fill().add(theLabel);
layout.row().center().fill().add(theTextField);
layout.row().center().fill().add(theScrollPane);

This should exactly behave as you describe.

Each call to row() creates a new row in the panel.

The calls to fill() make sure that each component uses the whole available width.

A few advantages of using DesignGridLayout here are:

  • only one LayoutManager for the whole panel
  • automatic borders and inter-rows spacing
jfpoilpret
thanks... when I'm willing to pull in a library, I use javabuilders + MiGlayout, this question was really about built-in layout managers, although I admit I didn't state that.
Jason S