我正在尝试在 Java 中实现 GridBagLayout 以实现我必须为我正在构建的程序制作的登录对话框。我要进行干净的 Google 登录。我遇到的主要问题是我设置的约束GridBagConstraints
不起作用。这是我希望对话框的样子。
这是我要实现的对话框的代码。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login_Dialog extends JDialog{
// SEtting up the required components for the sign in
/**
*
*/
private static final long serialVersionUID = 1L;
protected JLabel username_Label = new JLabel("Username");
protected JLabel password_Label = new JLabel("Username");
protected JTextField username_Field = new JTextField(30);
protected JTextField password_Field = new JTextField(30);
protected JButton sign_In = new JButton("Sign in!");
public Login_Dialog() {
setSize(600,400);
setTitle("Sign in");
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
add(username_Label);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
add(username_Field);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 2;
add(password_Label);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 4;
add(password_Field);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 5;
add(sign_In);
setVisible(true);
}
}
更新:
我做了一些改变,似乎我达到了我想要的结果。现在的问题是一切都居中并且按钮的长度太宽。另外,我希望文本字段和标签更大。
这是更新的GridBagLayout
//cusotmization of buttons
Dimension signD = sign_In.getPreferredSize();
signD.height = 50;
signD.width = 30;
sign_In.setPreferredSize(signD);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
add(username_Label,c);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 1;
add(username_Field,c);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 2;
add(password_Label,c);
c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 3;
add(password_Field,c);
//
// c.fill = GridBagConstraints.HORIZONTAL;
// c.weightx = 0.5;
c.gridx = 0;
c.gridy = 5;
//
add(sign_In,c);