0

I would like to add components by doing this:

frame.add(new JButton("Click here"));

But how would I add an ActionListener then? I assume it might have to do with AbstractButton instantiation?

I don't want to instantiate a JButton variable, so I'm not sure if this is the proper way to do it:

    frame.add(new JButton("Click here"), new AbstractButton() {
        public void addActionListener(ActionListener l) {
            // do stuff
        }
    });

If this works, I need it to be added in the actionPerformed() like this:

JButton button = new JButton("Click here");
button.addActionListener(this);

Note, that I'm not trying to do anonymous inner class for the ActionListener, but just a code simplification to add the component to the actionPerformed().

Is there any way to do this?

Thanks

6rchid
  • 1,074
  • 14
  • 19
  • Possible duplicate of [Can I add an ActionListener to a JButton that is not explicitely defined?](https://stackoverflow.com/questions/23530056/can-i-add-an-actionlistener-to-a-jbutton-that-is-not-explicitely-defined) – Malte Hartwig Mar 05 '18 at 10:47

1 Answers1

3

Three Options:

Option 1: In my opinion the cleanest

    JFrame frame = new JFrame();

    JButton button = new JButton("Click Here");
    frame.add(button);
    button.addActionListener(this);

Option 2 Anonymous class

    JFrame frame = new JFrame();

    JButton button = new JButton("Click Here");
    frame.add(button);

    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Clicked");
        }
});

Option 3

This is not recommended, ugly and has unintended side effects (imagine calling add again). But you asked for a way to do it directly inside the add.

    JFrame frame = new JFrame();

    JButton button = new JButton("Click Here");
    frame.add(new JButton("Click Here"){
        @Override
        public void addActionListener(ActionListener l) {
            super.addActionListener(YourClass.this);
        }
    });
lwi
  • 1,682
  • 12
  • 21