用javaswing写一个登录代码
时间: 2024-03-23 09:42:28 浏览: 14
好的,下面是一个简单的Java Swing登录代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame implements ActionListener {
private JLabel accountLabel = new JLabel("账号");
private JLabel passwordLabel = new JLabel("密码");
private JTextField accountField = new JTextField(20);
private JPasswordField passwordField = new JPasswordField(20);
private JButton loginButton = new JButton("登录");
private JButton cancelButton = new JButton("取消");
public LoginFrame() {
setTitle("登录");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 5, 5);
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(accountLabel, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
panel.add(accountField, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(passwordLabel, constraints);
constraints.gridx = 1;
constraints.gridy = 1;
panel.add(passwordField, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
panel.add(loginButton, constraints);
constraints.gridx = 1;
constraints.gridy = 2;
panel.add(cancelButton, constraints);
add(panel, BorderLayout.CENTER);
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String account = accountField.getText();
String password = new String(passwordField.getPassword());
// 在这里实现登录验证逻辑
if (account.equals("admin") && password.equals("admin123")) {
JOptionPane.showMessageDialog(this, "登录成功");
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误");
}
} else if (e.getSource() == cancelButton) {
System.exit(0);
}
}
public static void main(String[] args) {
LoginFrame frame = new LoginFrame();
frame.setVisible(true);
}
}
```
这个代码示例实现了一个简单的登录界面,包含了账号、密码、登录和取消按钮。当用户点击登录按钮时,程序会获取账号和密码并进行验证,如果验证通过则弹出登录成功提示框,否则弹出用户名或密码错误提示框。如果用户点击取消按钮,则程序退出。
这只是一个简单的示例,实际的登录功能可能还需要更多的验证和处理逻辑。您可以根据实际情况进行修改和扩展。