Question

I have got confused by these lines of code:

public class AL extends Frame implements WindowListener,ActionListener {
Button b;
b = new Button("Click me");
b.addActionListener(this);
...

what I understand is that the frame is set as event handler to "its" button. Is it acceptable to set event handlers that are themselves part of the gui while separate from the source of event?(I mean maybe a button class should handle its events.) As I have seen many of the events in codes are handled by the jframe. Is there any special purpose behind it? previously thanks for your time!

Was it helpful?

Solution

The reason you see such code (I've seen a lot of it too, I admit), is that some programmers, especially those writing AWT and/or Swing code, tend to put tons of GUI logic into a single class. The reasons for this vary, but several common ones are:

  • They've seen such code in examples while learning
  • They're reluctant to use anonymous classes, or perhaps there's so much code in the event listener's methods that an anonymous class doesn't seem applicable
  • They believe it's "easier" to understand the code, if the event handling of all child components is done directly in the parent container's methods
  • They're afraid to have "too many classes" in the project (I'd like to find whoever started that misconception !)

From my experience, a lot of GUI code looks like that. Is that a good way of programming ? ABSOLUTELY NOT !

Any methodology book you read will tell you the same. Such classes are breaking every possible principle of good design. The most basic example would be SRP (http://en.wikipedia.org/wiki/Single_responsibility_principle).

Moreover, GUI classes that handle events as methods of the class, tend to blow out of proportion, and unfortunately, classes of several thousands of lines of code is something I've seen many times in different projects and companies.

Don't fall into this trap. Keep your classes short, have a different class for each of the inner components, unless it's a regular component with a very simple initialization (in which case it would still be preferable to have a factory class do the initialization).

Keep event handling in anonymous classes when there's very few lines of code in the handler, and in separate classes when there's more than a line or two of code.

In short, GUI code is no different than other OO code, and should adhere to the same principles and methodologies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top