user2183935
user2183935

Reputation: 105

Which is the right way to handle events in JAVA?

Wich is the right way, the programmers use to handle events in JAVA? The question is, is it OK, to auto generate code double-clicking button in design view of Eclipse like this

btn_add_game.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

MY CODE TO EXECUTE;
            }
        });

or it's necessery to write the class that implements action listener and then write the code?

Also, on the same subject, is it normal to use Designer view in eclipse or hard-core programmers use code only?

Upvotes: 4

Views: 126

Answers (3)

Masudul
Masudul

Reputation: 21961

It depends on your need.

  1. If there is one action than use directly, as you show at your question.
  2. If there is multiple action than you should implements ActionListener for maintenance and reduce boilerplate code.

Upvotes: 1

Laf
Laf

Reputation: 8205

It all depends on your company's policies, and how much you want your code to be separated into logical units. The code you have provided in your question is OK; it will allow you to handle the event.

However, I usually prefer having a separate class, which extends the listener interface I need, rather than having a bunch of annonymous inner classes. It generates cleaner code (in my opinion), and makes it easier to maintain, or add new functionalities later on. But keep in mind that this is only my opinion (Adam posted a perfectly valid answer which goes against my opinion).

As far as coding a GUI is concerned, I never use a GUI builder, I find I lack control over the GUI components, layout and behavior. I always code it by hand, using the appropriate LayoutManager, or combination of managers. But, if your user interface is simple enough, and you don't want to be spending time learning how to handle GUI in Java, then using a builder is a perfectly valid option.

Upvotes: 1

Adam Arold
Adam Arold

Reputation: 30528

What you have written is perfectly fine. It is an anonymous inner class and I don't think that having those around is a code smell.

Imagine if you have implemented all listeners as separate classes. You would have ended up with a proliferation of classes which are essentially anonymous functions (like labdas in other languages).

So yes, go ahead and use generated listeners.

You other question is a religious one. Half of the programmers will say don't use it the other half will tell you to use it. It all comes down as preference. If the Designer in question generates quality code then use it otherwise do not.

Upvotes: 1

Related Questions