jeudi 4 août 2011

A very simple example using FXML (JavaFX 2.0 b37)

update August 05, 2011: cleaner code and runs in b38.
This example is a very simple JavaFX application using FXML. It could certainly be improved, but it's just enough to begin to play.

The application is made up of 3 files, which are:
·         The FXML file

Screen1.xml
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import fxml.MyGroup?> 

<MyGroup xmlns:fx="http://javafx.com/fxml">    
    <children>      
        <Button text="Click Me!" onAction="#handleButtonAction" />
        <Label  fx:id="label" translateX="0" translateY="30" text=""/>  
    </children>
</MyGroup >    

·         The Java class which maps the MyGroup's tag in the FXML file and handles the button’s event
MyGroup.java
package fxml;

import java.net.URL;
import java.util.Map;
import javafx.event.ActionEvent;
import javafx.fxml.Bindable;
import javafx.fxml.FXML;
import javafx.fxml.Resources;
import javafx.scene.Group;
import javafx.scene.control.Label;


public class MyGroup extends Group implements Bindable{
    
    @FXML private Label label;
    
    @FXML private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        label.setText("Hello World !");        
    }

   public void initialize(Map<String, Object> namespace, URL location, Resources resources) {
     
    }
}

·         The main class which loads the FXML file, transforms it to JavaFX object graph and adds it in to the scene of the JavaFX application.
TestFXML.java
package fxml;

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class TestFXML extends Application {

    public static void main(String[] args) {
        Application.launch(TestFXML.class, args);
    }

    @Override
    public void start(Stage primaryStage) {
        
        MyGroup myGroup = null;
        
        try{
            myGroup = (MyGroup) FXMLLoader.load(TestFXML.class.getResource("fxml/Screen1.xml"));
        }catch (IOException ioe){
            ioe.printStackTrace();
        }

        primaryStage.setTitle("Test FXML");
        primaryStage.setWidth(320);
        primaryStage.setHeight(200);

        Scene scene = new Scene(myGroup);
        primaryStage.setScene(scene);

        primaryStage.setVisible(true);
    }
}



Note: All that I have coded for this small example is based on: Introduction FXML from Jonathan Giles

2 commentaires:

Javin Paul a dit…

Thanks for this example man, there is not much resource on Java FX.

Javin
Difference between ClassNotFoundException vs NoClassDefFoundError

Bill a dit…

This example appears obsolete in the current JavaFX release. Bindable is now Initializable, and you need to add fx:controller="fxml.MyGroup" to the MyGroup node in order for the binding to occur.