开发者

swing: appropriate layout manager for simple situation?

开发者 https://www.devze.com 2022-12-20 12:59 出处:网络
I have a JPanel that I want to use to contain 3 vertical components: a JLabel a JTextField a JScrollPane

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开发者_JAVA百科 do?


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.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消