我使用GridBagLayout
将JButton
、JLabels
和JTextFields
对齐到登录表单中。但有时所有对象都会塞进一行。(并非总是随机发生,但经常无法忽略)。
这是我调整物体的方法
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
}
}
有什么建议吗?它看起来像什么/应该像什么的图像如下
有时它也这样做:
这是随机发生的,但往往无法忽视。有什么建议吗?
setViable(...)
。pack()