Making JavaFX Applications Fly Outside the Browser
The new out-of-process applet plugin in JavaSE 6 update 10 enables you to create applets that can be dragged out of the browser like widgets. However, you can also use this new feature to create applets that jump out of the browser to do other fun things. This example shows you how to create a flying saucer that escapes from the browser, flies around a bit, and then returns back to land. Note: This sample requires Java SE 6 update 10 or higher
| . | . |
Understanding the Code
To create a JavaFX application requires nothing special. Any application can be an applet if you put it in a web page. However, to make your application draggable when using JavaSE 6 update 10 requires using a special extension to the Stage class called AppletStageExtension. This class enables you to customize the drag behavior of your application.
First, put an instance of the AppletStageExtension class in the extensions variable of your application's Stage class. Then override the functions of AppletStageExtension that you care about. For this example, I wanted to make the applet "jump" out of the browser when the user presses the mouse button. To do achieve this goal, I set a handler for the shouldDragStart function. The handler returns true if the primaryMouseButton is down and if the applet is not already out of the browser. The flying animation should start after the user has released the mouse button. To enable that action, I set a handler for the onDragFinished function, which sets alreadyStarted to true and calls doFly() to start the animation, as shown in Figure 1.
import javafx.stage.Stage;
import javafx.stage.AppletStageExtension;
var alreadyStarted = false;
var stage = Stage {
x: 400
y: 300
width: 200
height: 200
style: StageStyle.TRANSPARENT
scene: Scene {
// the content of your application
}
extensions: [
AppletStageExtension {
shouldDragStart: function(e: MouseEvent): Boolean {
println("should drag start");
return e.primaryButtonDown and not alreadyStarted;
}
//onDragStarted: function(): Void {
// println("drag started");
//}
onDragFinished: function(): Void {
println("drag finished");
alreadyStarted = true;
currentImage = onImage;
doFly(stage.x,stage.y);
}
//onAppletRestored: function(): Void {
// println("restored");
//}
useDefaultClose: false
}
]
}
Animating the Flying Saucer
Because I don't care about when the drag gesture starts or when the applet is closed, I didn't set the onDragStarted or onAppletRestored handlers. It's okay to leave features you don't need unset.
After the applet is actually out of the browser, the doFly() animation takes over, which just moves the stage.x and stage.y over time to create the animation you see.
Josh MarinacciStaff Engineer,
Sun Microsystems