用java写一个登陆弹窗要代码
时间: 2024-05-02 13:18:14 浏览: 12
以下是一个简单的登陆弹窗的Java代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog implements ActionListener {
private final JTextField usernameField;
private final JPasswordField passwordField;
private boolean succeeded;
public LoginDialog(Frame parent) {
super(parent, "Login", true);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(10, 10, 10, 10);
JLabel usernameLabel = new JLabel("Username: ");
constraints.gridx = 0;
constraints.gridy = 0;
panel.add(usernameLabel, constraints);
usernameField = new JTextField(20);
constraints.gridx = 1;
constraints.gridy = 0;
panel.add(usernameField, constraints);
JLabel passwordLabel = new JLabel("Password: ");
constraints.gridx = 0;
constraints.gridy = 1;
panel.add(passwordLabel, constraints);
passwordField = new JPasswordField(20);
constraints.gridx = 1;
constraints.gridy = 1;
panel.add(passwordField, constraints);
passwordField.addActionListener(this);
JButton loginButton = new JButton("Login");
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
panel.add(loginButton, constraints);
loginButton.addActionListener(this);
getContentPane().add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
setLocationRelativeTo(parent);
}
public void actionPerformed(ActionEvent e) {
if (authenticate(usernameField.getText(), passwordField.getPassword())) {
succeeded = true;
dispose();
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password", "Login Error", JOptionPane.ERROR_MESSAGE);
usernameField.setText("");
passwordField.setText("");
}
}
private boolean authenticate(String username, char[] password) {
// 实现验证逻辑,返回true或false
}
public boolean showDialog() {
setVisible(true);
return succeeded;
}
}
```
使用该类的示例:
```
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton loginButton = new JButton("Open Login Dialog");
loginButton.addActionListener(event -> {
LoginDialog dialog = new LoginDialog(frame);
if (dialog.showDialog()) {
JOptionPane.showMessageDialog(frame, "Login succeeded");
} else {
JOptionPane.showMessageDialog(frame, "Login canceled");
}
});
frame.getContentPane().add(loginButton, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
```