把actionPerformed放到另一个类里
时间: 2023-08-12 15:05:13 浏览: 80
好的,以下是将 `actionPerformed` 放到另一个类中的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class LoginController implements ActionListener {
private final JTextField usernameField;
private final JPasswordField passwordField;
public LoginController(JTextField usernameField, JPasswordField passwordField) {
this.usernameField = usernameField;
this.passwordField = passwordField;
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("取消")) {
System.exit(0);
} else if (e.getActionCommand().equals("确定")) {
String username = usernameField.getText();
String password = String.valueOf(passwordField.getPassword());
if (username.equals("zhangsan") && password.equals("123")) {
JOptionPane.showMessageDialog(null, "欢迎使用");
} else {
JOptionPane.showMessageDialog(null, "用户名和密码错误,请重新输入");
}
}
}
}
public class LoginSystem extends JFrame {
private final JTextField usernameField;
private final JPasswordField passwordField;
public LoginSystem() {
super("登录系统");
JLabel usernameLabel = new JLabel("用户名:");
JLabel passwordLabel = new JLabel("密 码:");
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
JButton loginButton = new JButton("确定");
JButton cancelButton = new JButton("取消");
LoginController controller = new LoginController(usernameField, passwordField);
loginButton.addActionListener(controller);
cancelButton.addActionListener(controller);
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(usernameLabel);
panel.add(usernameField);
panel.add(passwordLabel);
panel.add(passwordField);
panel.add(loginButton);
panel.add(cancelButton);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new LoginSystem();
}
}
```
在这个示例中,我们创建了一个名为 `LoginController` 的类,它实现了 `ActionListener` 接口,并将 `actionPerformed` 方法移动到了这个类中。我们还将 `usernameField` 和 `passwordField` 作为构造函数的参数传递到 `LoginController` 中,并将 `loginButton` 和 `cancelButton` 的 `ActionListener` 设置为 `LoginController` 的实例。
这种方式可以更好地分离逻辑,使代码更易于维护和扩展。
阅读全文