O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mirror an Application #97
Chapter 12, Miscellany
|
489
HACK
AWTEvent.ACTION_EVENT_MASK |
AWTEvent.MOUSE_EVENT_MASK
);
}
First,
openSender( )
creates a new
ObjectOutputStream
around the socket’s
output stream. Next, it creates a new
AWTEventListener
that takes each event
and tests if it is a mouse event; if so, this method writes it to the output
stream. Notice that the second argument of
addAWTEventListener( ) is two
event masks ORed together (using the
| operator).
Receive Mouse Events
Receiving events is the reverse of sending them. You must open a server
socket for the (sending) instance to connect to, and then pull the events off
of the network one by one and repost them to the system event queue:
public void openReceiver( ) throws Exception {
// receive events
ServerSocket server = new ServerSocket(6754);
Socket sock = server.accept( );
EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue( );
ObjectInputStream in = new ObjectInputStream(sock.getInputStream( ));
while(true ) {
AWTEvent evt = (AWTEvent) in.readObject( );
if(evt instanceof MouseEvent) {
MouseEvent me = (MouseEvent)evt;
MouseEvent me2 = new MouseEvent(
me.getComponent( ),
me.getID( ),
me.getWhen( ),
me.getModifiers( ),
me.getX( ),
me.getY( ),
me.getClickCount( ),
me.isPopupTrigger( ),
me.getButton( )
);
eq.postEvent(me2);
}
}
}
Notice that the events are not posted directly to the event queue. Since the
objects really belong to the other instance, they won’t work in this instance
properly—all of the internal object references will be wrong. However, you
can make an exact copy of the event just by creating a new one with the
arguments from the old one. Then the new event will work fine in this sec-
ond instance.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required