1

I'd like to use the new operator to create an instance of JPanel that implements ActionListener and directly overrides the actionPerformed method.

I tried

JPanel panel = new JPanel implements ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        // ...
    }
};

but that doesn't work because of a syntax error.

Of course I could just define a new class like JPanelWithActionListener and call this one with new, but is there any way to do it in just one line?

Michael
  • 41,989
  • 11
  • 82
  • 128
DonFuchs
  • 371
  • 2
  • 14
  • 2
    No, you need to have a (super) type to implement. In your case you'd need to define some kind of class/interface that inherits both `JPanel` and `ActionListener`. But if you already have it, I suggest to not use an anonymous inner class. – C-Otto Jan 22 '18 at 10:50
  • 3
    It's usually a questionable approach to have a panel implement `ActionListener` anyway. – daniu Jan 22 '18 at 11:01

1 Answers1

0

That is not possible in Java - there is no anonymous type in Java.

Your code new JPanel implements ActionListener() { /*...*/ }; is equivalent to this code.

class JPanelWithActionListener extends JPanel implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
    }
}
JPanel panle = new JPanelWithActionListener();

You want to create a new type JPanelWithActionListener without defining a class (so, that class is anonymous).

djm.im
  • 3,295
  • 4
  • 30
  • 45