Im using GridBagLayout
to align JButtons
, JLabels
, and JTextFields
into a login form. But sometimes all the objects get crammed into one line. (not allways, it happens randomly but too often to ignore).
this is how I'm aligning the objects
package test;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
public class ManagerMain {
public static JFrame frame = new JFrame("this is a frame");
private JLabel loginNameLB = new JLabel("username:");
private JLabel loginPasswordLB = new JLabel("password:");
private JTextField loginName = new JTextField();
private JPasswordField loginPassword = new JPasswordField();
private JButton loginBTN = new JButton("Login");
private JButton loginCreateBTN = new JButton("Create An Account");
private Container login = new Container();
//login is a container
public ManagerMain() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
login.setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.insets = new Insets(2, 2, 15, 15);
gbc1.weightx = 1.0;
gbc1.weightx = 1.0;
//user name label
gbc1.gridx = 0;
gbc1.gridy = 0;
gbc1.gridwidth = 1;
gbc1.gridheight = 1;
gbc1.fill = GridBagConstraints.VERTICAL;
gbc1.fill = GridBagConstraints.HORIZONTAL;
login.add(loginNameLB, gbc1);
//user name text field
gbc1.gridx = 1;
gbc1.gridy = 0;
gbc1.gridwidth = 2;
gbc1.gridheight = 1;
gbc1.fill = GridBagConstraints.VERTICAL;
gbc1.fill = GridBagConstraints.HORIZONTAL;
login.add(loginName, gbc1);
//password label
gbc1.gridx = 0;
gbc1.gridy = 1;
gbc1.gridwidth = 1;
gbc1.gridheight = 1;
gbc1.fill = GridBagConstraints.VERTICAL;
gbc1.fill = GridBagConstraints.HORIZONTAL;
login.add(loginPasswordLB, gbc1);
//password text field
gbc1.gridx = 1;
gbc1.gridy = 1;
gbc1.gridwidth = 2;
gbc1.gridheight = 1;
gbc1.fill = GridBagConstraints.VERTICAL;
gbc1.fill = GridBagConstraints.HORIZONTAL;
login.add(loginPassword, gbc1);
//login button
gbc1.gridx = 1;
gbc1.gridy = 2;
gbc1.gridwidth = 1;
gbc1.gridheight = 1;
gbc1.fill = GridBagConstraints.VERTICAL;
gbc1.fill = GridBagConstraints.HORIZONTAL;
login.add(loginBTN, gbc1);
//create account button
gbc1.gridx = 2;
gbc1.gridy = 2;
gbc1.gridwidth = 1;
gbc1.gridheight = 1;
gbc1.fill = GridBagConstraints.VERTICAL;
gbc1.fill = GridBagConstraints.HORIZONTAL;
login.add(loginCreateBTN, gbc1);
frame.add(login, BorderLayout.CENTER);//add container to frame
}
}
Any suggestions? Image of what it looks like / what it should look like is bellow
sometimes it does this also: