Share the ideas and thoughts, become united ...

Saturday, December 19, 2009

Raise the desired event in java - it's possible and easy

I, myself is a beginner in programming languages. So, i encounter problem now and then. Recently i have faced a very interesting problem. As you know it is pretty much easy in C# to raise the desire event (or you don't know). But i was wondering how to do it in JAVA. Well i found it pretty much amazingly easy !!!

you just have to call dispatchEvent(AWTEvent e).

Explanation : This method takes the event that you want to raise and dispatches it (handles it).

Sample Code:

public class MainWindow extends JFrame implements WindowListener {
/* properties + methods */
public MainWindow() {
// bla bla codes
this.addWindowListener(this); // i am listening this window and the event handler is also def. in this class
// more codes
}
public void windowClosing(WindowEvent e) { // an event handler
// codes ...
System.out.println("dude this window is closing... save it.."); // code i am going to execute
// and still coding
}
public void raiseWindowCloseEvnt() { // user def. fn to raise the event
// last words before you close your window :)
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); // will i am dispatching a new event which is associated with this window (via this pointer). and i am likely to raise the Window_Closing event. Now i can raise the event just by calling this function.
}
public static void main(String[] args) {
MainWindow mw = new MainWindow();
mw.setVisible(true);
mw.raiseWindowCloseEvnt(); // see the output console :D
}
}

Pretty much easy isn't it? :)

No comments:

Post a Comment