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

488
|
Chapter 12, Miscellany
#97 Mirror an Application
HACK
second instance. As with creating single-launch applications on Windows
[Hack #84], a network socket is the best choice for a shared resource because
you need it anyway to send the events:
public void start( ) {
try {
// send events
final Socket sock = new Socket("localhost",6754);
openSender(sock);
} catch (Exception ex) {
try {
openReceiver( );
} catch (Exception ex2) {
System.out.println("exception: " + ex);
}
}
}
The start( ) method here tries to open a socket on a known port number
(6754 in this case). If the socket can be opened, then that means there is a
program on the other end waiting for a connection, in which case the code
can call
openSender( ) to start sending events. If the socket cannot be
opened, then there is no other program and this is the first running instance.
In that case, you can call
openReceiver( ) and start waiting for another pro-
gram to connect.
Send Mouse Events
To send events, you first need an output stream to send them. The java.io
package helpfully provides the ObjectOutputStream. It will take any Java
object, serialize it, and write it to the stream the class represents. Next, you
need to capture all relevant events and prepare them to go out. The AWT
Toolkit object lets you add listeners for any set of AWT events you wish.
You just need to OR together masks for the event types you want:
public void openSender(Socket sock) throws Exception {
final ObjectOutputStream out = new
ObjectOutputStream(sock.getOutputStream( ));
Toolkit.getDefaultToolkit( ).addAWTEventListener(
new AWTEventListener( ) {
public void eventDispatched(AWTEvent evt) {
try {
if(evt instanceof MouseEvent) {
MouseEvent me = (MouseEvent)evt;
out.writeObject(evt);
}
} catch (Exception ex) { }
}
},

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