写一个简单的java登录界面
时间: 2024-03-13 16:45:15 浏览: 26
好的,以下是一个简单的Java登录界面的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton;
public LoginFrame() {
setTitle("登录");
setLayout(new GridLayout(3, 2, 10, 10));
// 添加用户名和密码输入框
JLabel usernameLabel = new JLabel("用户名:");
usernameField = new JTextField();
JLabel passwordLabel = new JLabel("密码:");
passwordField = new JPasswordField();
add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
// 添加登录按钮
loginButton = new JButton("登录");
loginButton.addActionListener(this);
add(new JLabel()); // 空白占位符
add(loginButton);
setSize(300, 150);
setLocationRelativeTo(null); // 窗口居中
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// 在这里编写登录验证逻辑,比如查询数据库等
// 如果验证通过,则关闭登录窗口,打开主窗口
dispose();
new MainFrame();
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
class MainFrame extends JFrame {
public MainFrame() {
setTitle("欢迎");
setSize(300, 200);
setLocationRelativeTo(null); // 窗口居中
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
```
这个示例代码中,我们使用了`JFrame`、`JTextField`、`JPasswordField`、`JButton`等Swing组件,通过`setLayout`方法设置了网格布局,将多个组件放到一个网格中展示。在登录按钮的`actionPerformed`方法中,我们可以编写登录验证逻辑,在验证通过后关闭登录窗口,打开主窗口。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)