wood burning stoves 2.0*
The moose likes Swing / AWT / SWT and the fly likes How to separate the design from event handling in swing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "How to separate the design from event handling in swing" Watch "How to separate the design from event handling in swing" New topic
Author

How to separate the design from event handling in swing

rastogi payam
Ranch Hand

Joined: May 09, 2011
Posts: 45

Hi All,

I am using eclipse with windows builder plugin to develop my desktop application. The plugin used is generating the entire code into a single java file for gui.Now, I want to have the separate file for event handling.
For example,
Lets say we have one button and one textfield (code generated in file-Main.java),on click of button, the textfield should be filled with "Hello" .
For that we need to add actionListener to button and need to create an anonymous class and add method actionPerformed(),I want to have this class implementing ActionListener in separate java file(to separate the code we need to have the reference of the button and textfield in event handling class).How to get that reference.


SCJP 1.6, OCPWCD 5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38107
    
  22
Have a look at this old post, and the links to older posts in it.
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

you handle events 4 ways that i know of
1. implement the listeners. you will find this can get long and complicated with lots of if else statements
2. anonymous inner class
3. named inner class //my favorite so far
4. a separate top level class.

i misunderstood your question. you can do that a couple different ways also
1. pass a reference to "this" to the listener and make a variable package access so the listener can access it
2. pass a reference to "this" to the listener and supply get methods //i would go with 1 instead

in other word you have to write a constructor for your event handler sort of like this
myEventHandler(MyClass parent){}

there might be other ways i am unaware of

of course if your main class and the listener class are in different folders it kind of complicates things
you will have to do imports, and option 1 would change to making the variables pulic.


SCJP
Visit my download page
 
jQuery in Action, 2nd edition
 
subject: How to separate the design from event handling in swing
 
Similar Threads
Can you help me to write better code ?
frame close operations (GUI)
Switch
JPanel to JPanel in a JFrame
non-static var from static context