简体   繁体   中英

Java Swing GridBagLayout

I've been learning Java Swing using GridBagLayout.

I have a main JFrame and add main JPanel, then I add subsequent JPanels/components to that main JPanel.

But anything I add it always positions to the center of the main panel (including while resize), which is not desired result.

Just a small snippet on the core code:

getContentPane().setLayout(new GridBagLayout());
JPanel panel = new JPanel(new GridBagLayout());
getContentPane().add(panel);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;

JTextField nameField = new JTextField(10);
panel.add(nameField, gbc)

Any feedback would be appreciated, thanks.

In the future, post a SSCCE when you have a problem. A small "snippet" of code generally doesn't help.

Read the section from the Swing tutorial on How to Use GridbagLayout . The part on "weightx/weighty" will explain why this happens.

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