![](/img/trans.png)
[英]Should my custom async task have synchronized access to what is passed into constructor?
[英]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.