Java Swing 创建一个表单,这个表单纵向展示,有账号、密码的输入框,还有确定和取消两个按钮
时间: 2024-06-09 09:11:29 浏览: 142
下面是一个简单的 Java Swing 表单示例,包含账号、密码的输入框,确定和取消按钮。表单纵向展示,使用了 GroupLayout 布局管理器。
```java
import javax.swing.*;
import java.awt.*;
public class FormExample extends JFrame {
private JTextField usernameField;
private JPasswordField passwordField;
public FormExample() {
initComponents();
}
private void initComponents() {
setTitle("表单示例");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建组件
JLabel usernameLabel = new JLabel("账号:");
JLabel passwordLabel = new JLabel("密码:");
usernameField = new JTextField();
passwordField = new JPasswordField();
JButton okButton = new JButton("确定");
JButton cancelButton = new JButton("取消");
// 设置布局管理器
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
// 添加组件到布局中
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(usernameLabel)
.addComponent(passwordLabel))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(usernameField)
.addComponent(passwordField)
.addGroup(layout.createSequentialGroup()
.addComponent(okButton)
.addComponent(cancelButton)))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(usernameLabel)
.addComponent(usernameField))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(passwordLabel)
.addComponent(passwordField))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(okButton)
.addComponent(cancelButton))
);
// 显示窗口
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new FormExample();
}
}
```
运行程序,可以看到如下的表单界面:
![Java Swing 表单示例界面](https://img-blog.csdnimg.cn/20220101150850607.png)
阅读全文