gpt4 book ai didi

java - 我可以将 ActionListener 添加到 jFrame 中的按钮并在不同的类中使用 actionPerformed 方法吗?

转载 作者:行者123 更新时间:2023-11-29 04:12:35 24 4
gpt4 key购买 nike

我有一个 jFrame,用户可以在其中输入他们的数据,还有一个 Controller 类,我想在其中将该数据输入到一个新对象中。目前,我已经为 jFrame 中的按钮添加了一个监听器,但无法让它识别 Controller 类中的 actionPerformed 方法。

监听器的“this”部分声明它正在泄漏到构造函数中并且类本身声明:

"CreateAccountGUI is not abstract and does not override abstract method actionPerformed(actionEvent) in Action Listener"

我确实有其他按钮,但它们使用双击控件时提供的默认构造函数。

这是 jFrame 构造函数的代码:

public class CreateAccountGUI extends javax.swing.JFrame implements ActionListener{

/**
* Creates new form CreateAccountGUI
*/
public CreateAccountGUI() {
initComponents();
cboAccountType.setVisible(false);
lblAccountType.setVisible(false);
btnCreateAccount.addActionListener(this);
}

这是我目前在我希望 actionPerformed 方法驻留的类中的代码:

public class AccountStrategyController implements ActionListener, Observer{

private CreateAccountGUI view = null;

public void setView(CreateAccountGUI view){
this.view = view;
view.setVisible(true);//Show the account creation form
}

@Override
public void actionPerformed(ActionEvent e) {

}

我目前在这个类中没有任何错误。

我在网上看过,似乎您可以在不同的类中添加监听器和 actionPerformed,但我似乎无法理解它。

非常感谢任何帮助:)

最佳答案

你可以这样做:

public class CreateAccountGUI extends javax.swing.JFrame {

public CreateAccountGUI() {
/**/
JButton btnCreateAccount = new JButton("Create");
AccountStrategyController controller = new AccountStrategyController();
controller.setView(this);
btnCreateAccount.addActionListener(controller);
}
}

class AccountStrategyController implements ActionListener{

private CreateAccountGUI view = null;

public void setView(CreateAccountGUI view){
this.view = view;
view.setVisible(true);//Show the account creation form
}

@Override
public void actionPerformed(ActionEvent e) {
//respond to button click
}
}

或者更好:

public class CreateAccountGUI extends javax.swing.JFrame {

public CreateAccountGUI() {
/**/
JButton btnCreateAccount = new JButton("Create");
AccountStrategyController controller = new AccountStrategyController();
controller.setView(this);
btnCreateAccount.addActionListener(controller.createAccountListener());
}
}

class AccountStrategyController{

private CreateAccountGUI view = null;

public void setView(CreateAccountGUI view){
this.view = view;
view.setVisible(true);//Show the account creation form
}

public ActionListener createAccountListener(){
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//respond to button click
}
};
}
}

createAccountListener 可以使用 lambdas 编写:

public  ActionListener createAccountListener(){     
return e -> {
//respond to button click
};
}

关于java - 我可以将 ActionListener 添加到 jFrame 中的按钮并在不同的类中使用 actionPerformed 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54154399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com