Mirror an Application #97
Chapter 12, Miscellany
|
487
HACK
them to disk, of course, but it would be even cooler to send them over the
network to another copy of the program. That way the two programs could
reuse each other’s events and become mirrors! With a global event queue
and a bit of serialization, this turns out to be quite easy.
To replicate events over the network, you need to do three things:
1. Capture all AWT events. This can be done with an
AWTEventListener.
2. Send the event objects over the network.
3. Pick the objects up on the other end of the network and repost them in
the second program.
It sounds pretty simple, but there are always a few dragons hiding in the
mist.
Set Up a Window
Every test program begins with a frame and a few components. This pro-
gram is no different, with
ApplicationMirrorTest (shown in Example 12-18)
creating a frame, button, and text field in its constructor.
Become a Server or Client
There is only one program, but it must run in two modes: one for sending
AWT events and one for receiving. If the program starts and it’s the first
instance running, then it should wait to receive events. If it’s the second
instance running, then it should send events instead. But how does the pro-
gram know if it is the first or second instance? The only real way is to look
for a shared resource. If the resource is already taken, then this must be the
Example 12-18. Simple test program for mirroring
public class ApplicationMirrorTest {
public ApplicationMirrorTest( ) {
JFrame frame = new JFrame( );
frame.getContentPane().setLayout(new FlowLayout( ));
final JButton button = new JButton("action generator");
frame.getContentPane( ).add(button);
JTextField tf = new JTextField("text field");
frame.getContentPane( ).add(tf);
frame.pack( );
frame.show( );
}

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.