6rchid
6rchid

Reputation: 1302

How to add an ActionListener while adding an Instantiation of a JComponent to a JContainer?

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

Upvotes: 0

Views: 62

Answers (1)

lwi
lwi

Reputation: 1712

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

Upvotes: 3

Related Questions