[英]What should be passed to the constructor as the source?
I have a FormPanel class with a JButton, which has an ActionListener. 我有一个带有JButton的FormPanel类,该类具有ActionListener。 I also have a subclass of EventObject calles FormPanelEvent.
我还有一个EventObject的子类,称为FormPanelEvent。 My question is about the ActionListeners' actionPerformed() method: If I instantiate FormPanelEvent, do I pass the FormPanel object or the JButton as the source?
我的问题是有关ActionListeners的actionPerformed()方法的:如果我实例化FormPanelEvent,是否将FormPanel对象或JButton作为源? I have seen other people pass 'this', but isn't the JButton the actual source?
我见过其他人通过“ 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)
}
});
...
}
It depends on what you want to do with FormPanel
in the FormPanelEvent
. 这取决于您要在
FormPanel
中使用FormPanelEvent
做什么。 It want the complete functionality available in FormPanelEvent
class then you can pass this
otherwise if you want to play with source Ie Button only then you can pass submitButton
. 它想要
FormPanelEvent
类中可用的完整功能,则可以传递this
函数,否则,如果只想与源Ie Button一起播放,则可以传递submitButton
。
According to your code, it is more likely that submitButton
is the source for the event because the starting event is raised when you click on the button. 根据您的代码,更有可能的是事件的来源是
submitButton
,因为单击按钮时引发了启动事件。
You need to make submit button final
or a member field of the class in order to have an explicit access to it's reference in that actionListener anonymous class. 您需要使Submit按钮成为类的
final
或Member域,以便在该actionListener匿名类中对其的引用具有显式访问权。
Good Luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.