Event-Handling: Using one single class for different events?
Hi!
I am rather new to Java, so please, don't blame me for this question.
What I want is to seperate the GUI- from the Application code. Hence,
I have created three classes:
1. a Main class
2. a MainFrameCommand class, which parses the events
3. a MainFrameGUI class, that creates and paints the gui
(for a trivial example see end of this post)
Now, my question is this: Is it correct, to put all the various events
into one single command class (i.e, Focus-, Key-, Mouse-, and Windows-
Events) and then register the various event-listeners using this
single class?
It works perfectly, however, I wonder if this is a legal way to do so,
or is it necessary to create a seperate class for every different
event-listener-type?
Example:
------------------------------------------------------------
1. Main Class
------------------------------------------------------------
class Main {
public static void main(final String[] args) {
MainFrameCommand cmd = new MainFrameCommand();
MainFrameGUI gui = new MainFrameGUI(cmd);
}
}
------------------------------------------------------------
2. MainFrameCommand Class
------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
class MainFrameCommand
implements KeyListener, MouseMotionListener, WindowListener {
/* Key Listener */
public void keyPressed(KeyEvent event) {}
public void keyReleased(KeyEvent event) {}
public void keyTyped(KeyEvent event) {}
/* MouseMotion Listener */
public void mouseMoved(MouseEvent event) {}
public void mouseDragged(MouseEvent event) {}
/* WindowListener */
public void windowClosed(WindowEvent event) {}
public void windowOpened(WindowEvent event) {}
public void windowClosing(WindowEvent event) {}
public void windowActivated(WindowEvent event) {}
public void windowDeactivated(WindowEvent event) {}
public void windowIconified(WindowEvent event) {}
public void windowDeiconified(WindowEvent event) {}
}
------------------------------------------------------------
3. MainFrameGUI Class
------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
class MainFrameGUI extends Frame {
public MainFrameGUI(MainFrameCommand cmd) {
super("Window");
setSize(300, 300);
setVisible(true);
/* !!!!!!!!!!!!!!!!!!!!!!! HERE'S THE CRUCIAL QUESTION
!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!! Is it legal to add register all these
!!!!!!!!!!!!!!!!!!!!!!! event listeners using the same object?!?
*/
addKeyListener(cmd);
addWindowListener(cmd);
addMouseMotionListener(cmd);
}
public void paint(Graphics g) {}
}