André Leria
André Leria

Reputation: 392

Set Object's attributes on its creation

I sometimes see code like this:

new myJFrame().setVisible(true);

I don't exactly know how it works, but it actually creates a myJFrame and sets it visible, as an alternative to setting it visible on its constructor.

What I would like to know is if there would be a way to do this on a JMenuItem or JButton to automatically assign it an ActionListener without having to explicitly declaring it first, as in:

myJMenu.add(new JMenuItem("Item").addActionListener(myActionListener));

Which, as far as I've tried, doesn't work.

I don't exactly need it to work, I would just like to know if it is possible, for it would save me some good time.

Thanks in advance.

Upvotes: 1

Views: 1952

Answers (4)

trashgod
trashgod

Reputation: 205785

As an alternative, consider using the JMenuItem constructor that takes an Action:

myJMenu.add(new JMenuItem(new AbstractAction("Item") {

    @Override
    public void actionPerformed(ActionEvent e) {
        ...
    }
});

Upvotes: 3

user949300
user949300

Reputation: 15729

Your proposed code won't work because JMenuItem.addActionListener() does not return anything (it's a void method), so there is nothing to pass as the argument to JMenu.add().

In the first example, there is also nothing returned, but it doesn't matter.

As mentioned by @biziclop, in some styles of coding most methods return this so that they can be chained together. For example, Builders which use a Fluent Interface tend to do this.

Upvotes: 3

Markus Mikkolainen
Markus Mikkolainen

Reputation: 3497

if you want nastiness you can do an anonymous extension of a non-final class and add an anonymous constructor to initialize stuff:

ArrayList ar=new ArrayList()  
    {
      {
        add(new Object());
      }
    };

Upvotes: 0

biziclop
biziclop

Reputation: 49734

It's called method chaining and simply put, a class either supports it or not, depending on how it's written.

The way it is done is simple:

public class Bar {

   private Set<Foo> foos;

   public Bar addFoo( Foo foo ) {
     this.foos.add( foo );
     return this;
   }
}

From this you can also see why it isn't possible to chain methods that weren't written this way.

Upvotes: 3

Related Questions