Skip to content
Advertisement

Java Swing `GridBagLayout` alignment issue

I’m trying to create a login form using Java Swing. But I want the layout to look tighter, but still responsive.

The structure of my project

JavaScript

This is the picture of the GUI, this is not what I want: enter image description here

The components in the form panel are not behaving as I would expect, I want the fields to be close to the labels but not filling the entire space horizontally.

And my code:

LoginPanel

JavaScript

Main

JavaScript

This is how I want it to look like(updated):

JavaScript

Advertisement

Answer

I want the fields to be close to the labels but not filling the entire space horizontally.

JavaScript

Don’t attempt to set a window size. All Swing components will determine their own preferred size. You add all the components to the frame and the pack() the frame BEFORE you invoke the setVisible(…) method. The frame will then be sized based on the preferred size of all the components.

JavaScript

Don’t use static variables. That is not how the static keyword should be used.

There is no need to create an instance variable for your labels. You generally only create instance variables when you want the variable to be reference in multiple methods. The label is just for display on the form. The text fields will be reference in the ActionListener of your button, so they should be instance variables.

JavaScript

Don’t attempt to set the size. The extra vertical height is because you just use 400 as the random height of the frame. The pack() method will determine the preferred size.

JavaScript

The number in the constructor will be used to size the text field to contain “W” characters. It is not pixels. So the values you specify are too large.

JavaScript

No need for the “fill” constraint.

JavaScript

No need to specify a maximum size.

I would also suggest that your entire layout can be done using the GridBagLayout.

For the label in the first row you would use a gridwidth = 2. Same for the button in the last row.

Then you can use the anchor constraint to control the alignment of the label/button on the row. That is do you want the label centered and the button right aligned.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement