【发布时间】:2014-12-06 22:03:00
【问题描述】:
我使用GridBagLayout 将JButtons、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
}
}
有什么建议吗?它的样子/应该是什么样子的图像如下所示
有时它也会这样做:
【问题讨论】:
-
为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)。
-
去掉gridwidth和gridheight入手
-
看起来布局已经被 FlowLayout 休息了
-
这就是我避免使用 Swing 布局管理器的原因(只需查看所有代码)。我建议你使用像 MigLayout 这样的第三方库。我意识到这并不能回答您的问题,您可能不想在项目中添加依赖项,但这只是一个建议。
-
@dramzy 你能用
MigLayout将我链接到一个好的教程/项目示例吗?
标签: java swing alignment layout-manager gridbaglayout