Saturday, March 9, 2013

Java swing with JavaFx

Enhance a Java swing frame with JavaFx componets or functionality

My purpose with this short blog to present a very simple example of how I was understood the use Java swing components together with Javafx components on a Java Frame form. So, I just was curios to see how can I improve a swing form with the new modern JavaFx componets or technology. Having this idea in my mind I have looked for technical documents at oracle javafx blog site, and I found the following 2 interesting articles:

More about javafx on: Oracle's site

Firs let me show you to picture about my running application, that tells you all, about my short example.

Image 1:

Image 2:

Now as you see above, just a short demonstration of how can we use together a javafx and a swing button on a JFrame form. With Netbeans IDE, the steps are easy primitve, but of course you can use your favorite IDE to try this also. I packed all the application in a zip file, so you can even download for free, if you want to look over.

First I created an empty, new JavaFx project, called javafxswingapplication1. Then you may wonder, but I created a new java file, not a javafx unit. This was an empty JFrame form, and I just put on it a swing button, a swing text field and also a JPanel swing container. The JPanel will hold the javafx components, designed on a JFXPanel. The “birdge” between the swing and javafx, is the JFXPanel javafx container, which can be added to the JPanel. The swing part of the form was designed with the swing designer from the Netbeans IDE, and the javafx code I added manually to the form.

All the javafx code is wrapped into a single method and is called from the constructor of the Jframe form, after the call of initcomponents() swing initialization method. The javafx project is set to start this frame at running the application. This can be done at project properties, run – main class.

So the key point is the javafx method, let's see how does it look. I was called this method: createSceneAndAddToSwing

private void createSceneAndAddToSwing() {
PlatformImpl.startup(new Runnable() {
public void run() {
jfxPanel = new JFXPanel();
Group mainPanel = new Group();
Scene scene = new Scene(mainPanel,300,150);
Button btn = new Button();
btn.setText("From JavaFX");
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
jTextField1.setText("It was pushed a JavaFX button!");

//add this "javafx" to the swing jframe's jpanel
jPanel1.setLayout(new BorderLayout());
jfxPanel.setPreferredSize(new Dimension(PANEL_WIDTH_INT, PANEL_HEIGHT_INT));
jPanel1.add(jfxPanel, BorderLayout.CENTER);
So that's it, for a more complex javafx functionality in a swing frame, I would firstly create a standalone javafx project to wirte and test the desired javafx and then to embed it onto a jpanel container using the JFXPanel as a bridge.

No comments:

Post a Comment