0

I have a FormPanel class with a JButton, which has an ActionListener. I also have a subclass of EventObject calles 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? I have seen other people pass 'this', but isn't the JButton the actual source?

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)
        }

    });

...
}
Ali Mustafa
  • 475
  • 1
  • 6
  • 13

2 Answers2

0

It depends on what you want to do with FormPanel in the FormPanelEvent. It want the complete functionality available in FormPanelEvent class then you can pass this otherwise if you want to play with source I.e. Button only then you can pass submitButton.

Garry
  • 4,493
  • 3
  • 28
  • 48
0

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.

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.

Good Luck.

STaefi
  • 4,297
  • 1
  • 25
  • 43