Sunday, July 01, 2012

Do You Remember When?... Closing Windows in Swing

I was just looking at some old Swing code. I mean some really old Swing code, and I found this interesting morsel of code which made me think back to when this was considered the standard mechanism for window management.

Today when we want to control the closing of a JFrame, we would use something like setDefaultCloseOperation(int operation). If we wanted the frame to close when someone clicked the "X", we would set it using setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE). The code I found was the old style of doing it, and it made me think about it. Here is the code snippet I found which would still work today.

Here are the rules for the implementation.

There are three elements that the event handling mechanism must employ:
  1. It must implement a listener interface, or extend a class that implements a listener interface.
  2. You must register an event handler class as a listener on one or more components.
  3. The event handler class has code that implements methods in the listener interface.
Does it meet the requirements? It sure does, and the code works today. It is part of my code cleanup for code I have kept since 1995, and I am deciding what is useful.
Update: I found this comment in the code too. It is still true and relevant, but I must have thought it important to document since there are so many little event handlers. Since it was not in source control, I have no idea when I wrote this. Perhaps when Swing came on the scene (1997)? Interesting historical note.
The event handler code should be minimized to allow the program to remain responsive to user input. The event handling code is handled on a single thread - event-dispatching thread. This thread also handles the paint and repainting of components. This may also result in "gray screens" while the system is waiting to repaint a component.


Popular Posts