繁体   English   中英

应该将什么作为源传递给构造函数?

[英]What should be passed to the constructor as the source?

我有一个带有JButton的FormPanel类,该类具有ActionListener。 我还有一个EventObject的子类,称为FormPanelEvent。 我的问题是有关ActionListeners的actionPerformed()方法的:如果我实例化FormPanelEvent,是否将FormPanel对象或JButton作为源? 我见过其他人通过“ this”,但是JButton不是真正的来源吗?

public class FormPanel extends JPanel {

private JLabel usernameLabel, passwordLabel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton submitButton, clearButton;

private Collection<FormPanelListener> formPanelListeners = new ArrayList<>();

public FormPanel() {

... 

    submitButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            String username = usernameField.getText().trim();
            char[] password = passwordField.getPassword();

            FormPanelEvent e = new FormPanelEvent(this or submitButton)
        }

    });

...
}

这取决于您要在FormPanel中使用FormPanelEvent做什么。 它想要FormPanelEvent类中可用的完整功能,则可以传递this函数,否则,如果只想与源Ie Button一起播放,则可以传递submitButton

根据您的代码,更有可能的是事件的来源是submitButton ,因为单击按钮时引发了启动事件。

您需要使Submit按钮成为类的final或Member域,以便在该actionListener匿名类中对其的引用具有显式访问权。

祝好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM