• Post Reply Bookmark Topic Watch Topic
  • New Topic

Listener Classes

 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have several class files in my SWING GUI. Some or even all may contain JCheckBoxes, JRadioButtons, etc. Components that require a listener. Anyway, I want to have only one Listener Class for each Component.
For instance, I may have 3 classes that use a JCheckBox and I want only one MyCheckBoxListener Class to listen for all the checkboxes in my GUI.
I know that within the classes I have to MyCheckBoxListener myListener = new MyCheckBoxListener() and then add myListener to each CheckBox.
My question is, is this correct procedure and what does that do in memory when I do MyCheckBoxListener myListener = new MyCheckBoxListener() X 3 - replacing myListener with 3 different names?

------------------
Happy Coding,
Gregg Bolinger
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gregg,
There is no right or wrong way to handle GUI callbacks. The only issue that might come up using your listener class is that it won't be able to interact with the component container parameters unless you make your listener class an inner class of the container class. What that means is that in most cases one GUI component will affect another one. For example selecting something in a choice list might enable/disable another component. If you have a listener class it can't get a handle for the other components.
Regards,
Manfred.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gregg,
Another approach, and my favorite, is to use anonymous inner classes that call class methods to perform the work. That way if you have say 50 buttons and 30 do the same thing they can all call the same method. A simple example follows.

Regards,
Manfred.
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replay Manfred. Here is how I interact with components from outside the class. And I'm sure that this is horrible code practice. But it works and I haven't had a problem yet.
If I need to interact with a component from outside the class I just make it public static Component. Now, let's say I have a class called MainFrame and I have JCheckBoxes inside that class. Well, here --

Ok, now I have my listener Class - A completely seperate file


Ok, go ahead and rip me a new one and tell me how horrible it is to have public components.

------------------
Happy Coding,
Gregg Bolinger
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!