利用盒式布局管理器设计实现用户登录页面
时间: 2023-12-11 12:04:34 浏览: 23
好的,以下是基于盒式布局管理器设计实现用户登录页面的示例代码:
```java
import javax.swing.*;
import java.awt.*;
public class LoginUI extends JFrame {
private JLabel userLabel, passLabel;
private JTextField userText;
private JPasswordField passText;
private JButton loginBtn, cancelBtn;
public LoginUI() {
super("用户登录");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建容器
Container container = getContentPane();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
// 创建用户标签和文本框
userLabel = new JLabel("用户名:");
userText = new JTextField(20);
JPanel userPanel = new JPanel();
userPanel.add(userLabel);
userPanel.add(userText);
// 创建密码标签和文本框
passLabel = new JLabel("密码:");
passText = new JPasswordField(20);
JPanel passPanel = new JPanel();
passPanel.add(passLabel);
passPanel.add(passText);
// 创建登录和取消按钮
loginBtn = new JButton("登录");
cancelBtn = new JButton("取消");
JPanel buttonPanel = new JPanel();
buttonPanel.add(loginBtn);
buttonPanel.add(cancelBtn);
// 添加组件到容器
container.add(Box.createVerticalStrut(20));
container.add(userPanel);
container.add(Box.createVerticalStrut(10));
container.add(passPanel);
container.add(Box.createVerticalStrut(20));
container.add(buttonPanel);
// 设置窗口大小和位置
setSize(300, 200);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new LoginUI();
}
}
```
在这个示例中,我们使用了BoxLayout来创建一个垂直的容器,并在其中添加了用户名标签和文本框、密码标签和文本框以及登录和取消按钮。使用Box.createVerticalStrut方法来设置组件之间的间距。最后,我们设置了窗口大小和位置,并将其显示出来。
你可以根据自己的需要进行修改和调整,比如添加图标、设置背景色等。