user1597002
user1597002

Reputation:

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.

Upvotes: 1

Views: 107

Answers (1)

camickr
camickr

Reputation: 324197

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.

Upvotes: 3

Related Questions