0

I have a class named “FormPanel.java” that extends JPanel. This class create an information entry form with some JTextFields, a ComboBoxes, a JList, and a JButton named "submitBtn". After filling the form, JButton should be pressed for processing that info. So I add an action listener to my JButton. As I have some other components that need listeners for handling their events, so I define an addListeners() method in my FormPanel class, and there I create JButton listener as below:

public class FormPanel extends JPanel {
/* some codes here*/

  private void addListeners() {
        submitBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {        
                FormEvent = new FormEvent(this,emptxtField,emptxtField);
                /* and there are some lines of codes here */
                System.out.println(this);
                formEventAccured(ev);               
                //this.formEventAccured(ev);
            }
        });
        /*and some other listeners in here*/
    }
/* some codes here*/

    public void formEventAccured(FormEvent e) {
        //…
    }
}

formEventAccured(FormEvent e) is a public method in FormPanel class. Problem is here: in the actionPerformed method, if I call formEventAccured method as “formEventAccured(ev)” everything goes fine, but if I call it as “this.formEventAccured(ev)” it cause error! Even though I print “this” object and it was FormPanel Class not an ActionListener!

sysout result:

 FormPanel$1@1bc7e86

Error: the method formEventAccured(FormEvent) is undefined for the type new ActionListener(){}

Since formEventAccured is a public method of the FormPanel class, and printing "this" show that it is FormPanel object, so why calling it as “this.formEventAccured(ev)” will cause an error?! Thanks.

feel free
  • 173
  • 1
  • 10
  • 4
    `this` within your `actionPerformed` method actually refers to your created anonymous subclass of `ActionListener` created by `new ActionListener() {...}`). The answers to the linked question explain more of it. – MC Emperor Nov 11 '18 at 13:34
  • 2
    It should be `FormPanel.this` to refer to the outer class – Hovercraft Full Of Eels Nov 11 '18 at 13:34
  • "and printing "this" show that it is FormPanel object". Where exactly did you print that? In the presence of inner classes, depending on which method you printed from `this` will be different. – Thilo Nov 11 '18 at 13:35
  • yes i do! result was: FormPanel$1@1bc7e86 – feel free Nov 11 '18 at 13:36
  • 2
    You're not understanding the `$1` part -- **that represents the inner class**. So your printing is in fact showing that `this` does **not** represent the FormPanel object. – Hovercraft Full Of Eels Nov 11 '18 at 13:41

0 Answers0