File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark ""Global Fields" used in listeners" Watch ""Global Fields" used in listeners" New topic

"Global Fields" used in listeners

Lance Finney
Ranch Hand

Joined: Apr 26, 2001
Posts: 133
I have a gui that uses a couple ActionListeners to respond to button clicks. Within those listeners, I use values entered in fields on the JFrame. I'm currently creating the listeners as inner classes and making the text fields private class variables so the listeners have access to them. I'm concerned about this approach because I'd rather have the text fields local to the methods that create them. This will be a problem if I later decide to pull those Inner Classes out to their own files. Basically, I'm concerned that I'm not following good MVC principles by coupling the listeners to the text fields. Is there a way to do this without using a bunch of getParent() calls on the event?
Here's a simplified version of my code:

Is there a way to use a value from bookText in the listener without doing this?
[This message has been edited by Lance Finney (edited October 18, 2001).]
Paul Stevens
Ranch Hand

Joined: May 17, 2001
Posts: 2823
Another option would be to make your buttons ActionListener anonymous and just execute a method within your main class.
Lance Finney
Ranch Hand

Joined: Apr 26, 2001
Posts: 133
I thought about using anonymous inner classes, but the code I have is much more complex than what I showed in the simplified code. Because of that, I'd rather not have such complicated code buried in the anonymous class.
Another option would be to have Prototype implement the listeners directly. Maybe I'll just have to do that.
I agree. Here's the link:
subject: "Global Fields" used in listeners
It's not a secret anymore!