现在我有一个登录用户。 JFrame设置。用户名和密码有2个标签和2个字段。它们居中并且如此:
username: |text field|
password: |text field|
JPanel loginLabel = new JPanel(new GridLayout(0, 1, 0, 10));
loginLabel.add(usernameLabel);
loginLabel.add(passwordLabel);
loginLabel.setBackground(new Color(82,80,80));
JPanel loginField = new JPanel(new GridLayout(0, 1, 0, 10));
loginField.add(usernameField);
loginField.add(passwordField);
loginField.setBackground(new Color(82,80,80));
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(createButton);
buttonPanel.add(loginButton);
buttonPanel.add(quitButton);
buttonPanel.setBackground(new Color(82,80,80));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
setBackground(new Color(82,80,80));
add(loginLabel, BorderLayout.CENTER);
add(loginField, BorderLayout.LINE_END);
add(buttonPanel, BorderLayout.SOUTH);
我试图让它在所有标签和字段都居中的地方,但它们看起来像这样:
Username
|Text Field|
Password
|Text Field|
任何人都可以帮忙吗?
答案 0 :(得分:0)
你可以尝试使用setBounds(x,y,length,heigth),你必须setLayout(null)
答案 1 :(得分:0)
不要同时使用GridLayout
或FlowLayout
。他们没有任何好处。我建议使用GroupLayout
或MigLayout
。
我使用内置的GroupLayout
管理器创建了一个解决方案。它是一个现代而灵活的布局管理器。
package com.zetcode;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class GroupLayoutPasswordEx extends JFrame {
public GroupLayoutPasswordEx() {
initUI();
}
private void initUI() {
JLabel userLabel = new JLabel("User");
JTextField userField = new JTextField();
JLabel pswdLabel = new JLabel("Password");
JPasswordField pswdField = new JPasswordField();
createLayout(userLabel, userField, pswdLabel, pswdField);
setTitle("Login");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
Container pane = getContentPane();
GroupLayout gl = new GroupLayout(pane);
pane.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setAutoCreateGaps(true);
gl.setHorizontalGroup(gl.createParallelGroup(GroupLayout.Alignment.CENTER)
.addComponent(arg[0])
.addComponent(arg[1])
.addComponent(arg[2])
.addComponent(arg[3])
);
gl.setVerticalGroup(gl.createSequentialGroup()
.addComponent(arg[0])
.addComponent(arg[1], GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(arg[2])
.addComponent(arg[3], GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
GroupLayoutPasswordEx ex = new GroupLayoutPasswordEx();
ex.setVisible(true);
});
}
}
一旦你向这位经理投入一些时间,这并不困难。 这是截图: