简体   繁体   中英

Using GridBagLayout to arrange components of a JPanel vertically

I'm making a program. Is it is possible to arrange components of a JPanel vertically?

This is for a label. I would like a label to be shown on top of a text field without having to create another JPanel for it. Also, I am using GridBagLayout and CardLayout to arrange and switch out my JPanels .

You could simply use GridBagConstraints#gridwidth set to GridBagConstraints.REMAINDER ...

setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
add(new JLabel("Happy as can be"), gbc);
add(new JTextField(10), gbc);
add(new JLabel("Happy place"), gbc);
// etc..

Take a look at How to Use GridBagLayout for more details

Set GridBagLayout's options: Columns Weight [1]; Rows Height [30, 40, 50, 1] for each line a specified value of height you want, last row put 1 to using Rows Weight and set its Rows Weight [0, 0, 0, 1] then set component's anchor to northwest, Fill: horizontal or both; Finally set component X, Y to put component to grid bag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM