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

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

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

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

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.
package fxml;

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);

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

        primaryStage.setTitle("Test FXML");

        Scene scene = new Scene(myGroup);


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.

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.