下面是使用GridLayout
private void init() {
JFrame frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField loginUNTextField = new JTextField();
JTextField loginPTextField = new JTextField();
JTextField registerUNTextField = new JTextField();
JTextField registerPTextField = new JTextField();
JTextField registerETextField = new JTextField();
JButton login = new JButton("Login");
JButton register = new JButton("Register");
JLabel loginUsername = new JLabel("Username");
JLabel loginPassword = new JLabel("Password");
JLabel registerUsername = new JLabel("Username");
JLabel registerPassword = new JLabel("Password");
JLabel registerEmail = new JLabel("Email");
JPanel loginUNPanel = new JPanel(new GridLayout(3,2));
loginUNPanel.add(loginUsername);
loginUNPanel.add(loginUNTextField);
loginUNPanel.add(loginPassword); // Cause Problem
loginUNPanel.add(loginPTextField);
loginUNPanel.add(new JLabel("")); // Cause Problem
loginUNPanel.add(login);
JPanel registerUNPanel = new JPanel(new GridLayout(4,2));
registerUNPanel.add(registerUsername);
registerUNPanel.add(registerUNTextField);
registerUNPanel.add(registerPassword);
registerUNPanel.add(registerPTextField);
registerUNPanel.add(registerEmail);
registerUNPanel.add(registerETextField);
registerUNPanel.add(new JLabel(""));
registerUNPanel.add(register);
loginUNPanel.add(loginPassword);
JPanel main = new JPanel(new GridLayout(1,2));
main.add(loginUNPanel);
main.add(registerUNPanel);
frame.add(main);
frame.pack();
frame.setVisible(true);
}
欲望结果:
UserName | TextField
Passowrd | TextField
| LoginButon
请使用GridLayout
让我知道我在哪里。
答案 0 :(得分:2)
您正在向容器添加两次组件。
JPanel loginUNPanel = new JPanel(new GridLayout(3,2));
loginUNPanel.add(loginUsername);
loginUNPanel.add(loginUNTextField);
loginUNPanel.add(loginPassword); // ***** adding it once *****
loginUNPanel.add(loginPTextField);
loginUNPanel.add(new JLabel(""));
loginUNPanel.add(login);
JPanel registerUNPanel = new JPanel(new GridLayout(4,2));
registerUNPanel.add(registerUsername);
registerUNPanel.add(registerUNTextField);
registerUNPanel.add(registerPassword);
registerUNPanel.add(registerPTextField);
registerUNPanel.add(registerEmail);
registerUNPanel.add(registerETextField);
registerUNPanel.add(new JLabel(""));
registerUNPanel.add(register);
loginUNPanel.add(loginPassword); // ***** adding it again. *****
JPanel main = new JPanel(new GridLayout(1,2));
摆脱第二次加成:
// loginUNPanel.add(loginPassword); // *** this
JPanel main = new JPanel(new GridLayout(1,2));