Skip to main content

the fxjs logo - More UI Examples

These examples show how the code in Using JavaFX UI Controls can be rewritten in the fxjs logo. All of the examples have not been translated yet, but the list is growing! Use the index below to quickly find what you need.

ExamplePure JS
Button SampleYes
Checkbox SampleYes
ChoiceBox SampleYes
Label SampleYes
Layout Sans TearsYes
ListView SampleNo
Menu SampleYes
RadioButton SampleYes
ScrollBar SampleYes
ToggleButton SampleYes
TreeView SampleBoth

Running these Examples

Many of the examples in Using JavaFX UI Controls use custom icons and graphics. So, to avoid copyright or other IPR issues, they have not been physically incorporated into the examples. The rest of this sub-section describes a way of running these examples without infringing the terms of the copyright notice. The License.txt file from UIControlSamples.zip is reproduced at the bottom of this page.

Prerequisite Step

The actions described here must be performed once before any of the the fxjs logo examples can be run. This step results in the creation of a directory (called the demo-directory henceforth) in which all the examples will be run.

  • download the file UIControlSamples.zip from Oracle's JavaFX tutorials site
  • unzip UIControlSamples.zip into a convenient directory, and navigate to the src directory
  • the src directory is the demo-directory in which all the the fxjs logo examples will be run. You may freely rename this directory and/or move it to a more convenient location (the contents have no dependence on anything else)

Now download the latest FXJS.jar into the demo-directory. Run one of the following commands to verify that FXJS.jar and the JavaFX runtime library are both accessible.

unix> java -cp FXJS.jar:[jfxrt-path]:. fxjs.Main
windows> java -cp FXJS.jar;[jfxrt-path];. fxjs.Main

As usual, [jfxrt-path] should be replaced with the path to the file jfxrt.jar of the JavaFX library. When the command is run you should see the JavaFX window shown in Figure-1 below. This verifies that the classpath for the fxjs logo applications is set correctly.

the usage window
Figure-1. The usage message in a JavaFX window

Button Sample

This section describes a the fxjs logo implementation of the Button example. Before proceeding to run the example, verify that the demo-directory contains a directory named buttonsample, and that buttonsample contains two files named not.png and ok.png. Copy the following code into a file called ButtonSample.js in the demo-directory.

{T: fxStage, title: "Button Sample", width: 300, height: 190,
  scene: {T: fxScene, fxid: "scene",
    root: {T: fxGroup,
      children: [
        {T: fxVBox, spacing: 10, layoutX: 20, layoutY: 20,
          children: [
            {T: fxButton, fxid: "button1", text: "Accept", graphic: "this.imageAccept",
                style: "-fx-font: 22 arial; -fx-base: #b6e7c9;",
                onAction: function (e) {this.label.setText("Accepted");}},
            {T: fxHBox, spacing: 10,
              children: [
                {T: fxButton, text: "Accept",
                    onAction: function (e) {this.label.setText("Accepted");}},
                {T: fxButton, fxid: "button3", text: "Decline",
                    onAction: function (e) {this.label.setText("Declined");},
                    onMouseEntered: function (e) {this.button3.setEffect(this.shadow)},
                    onMouseExited: function (e) {this.button3.setEffect(null)}},
                {T: fxLabel, fxid: "label", fill: "this.color", 
                    font: {T: fxFont, name: "Times New Roman", size: 22}}
              ]
            },
            {T: fxHBox, spacing: 10,
              children: [
                {T: fxButton, graphic: "this.imageAccept2", 
                    onAction: function (e) {this.label.setText("Accepted");}},
                {T: fxButton, graphic: "this.imageDecline", 
                    onAction: function (e) {this.label.setText("Declined");}}
              ]
            },
            {T: fxHBox, spacing: 10},
          ]
        }
      ]
    }
  },

  imageAccept: new Packages.javafx.scene.image.ImageView(
      new Packages.javafx.scene.image.Image("file:buttonsample/ok.png")),
  imageAccept2: new Packages.javafx.scene.image.ImageView(
      new Packages.javafx.scene.image.Image("file:buttonsample/ok.png")),
  imageDecline: new Packages.javafx.scene.image.ImageView(
      new Packages.javafx.scene.image.Image("file:buttonsample/not.png")),
  color: Packages.javafx.scene.paint.Color.web("#464646"),
  shadow: new Packages.javafx.scene.effect.DropShadow()
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main ButtonSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-2 below should be displayed.

the ButtonSample window
Figure-2. The Button Sample window

Checkbox Sample

This section describes a the fxjs logo implementation of the Checkbox example. Before proceeding to run the example, verify that the demo-directory contains a directory named checkboxsample, and that checkboxsample contains three files named Chart.png, Project.png, and Security.png. Copy the following code into a file called CheckboxSample.js in the demo-directory.

{T: fxStage, title: "Checkbox Sample", width: 230, height: 120,
  scene: {T: fxScene,
    root: {T: fxGroup,
      children: [
        {T: fxHBox, spacing: 40, 
            padding: {T: fxInsets, top: 20, right: 10, bottom: 10, left: 20},
          children: [
            {T: fxVBox, spacing: 5, 
              children: [
                {T: fxCheckBox, text: "Security", onAction: "this.selection", 
                    userData: "this.icon1"},
                {T: fxCheckBox, text: "Project", onAction: "this.selection", 
                    userData: "this.icon2"},
                {T: fxCheckBox, text: "Chart", onAction: "this.selection", 
                    userData: "this.icon3"},
              ]
            },
            {T: fxStackPane, alignment: fxTOP_CENTER,
              children: [
                {T: fxRectangle, width: 90, height: 30, arcHeight: 10, arcWidth: 10,
                  fill: Packages.javafx.scene.paint.Color.rgb(41, 41, 41)},
                {T: fxHBox, padding: {T: fxInsets, top: 0, right: 0, bottom: 0, left: 5},
                  children: [
                    {T: fxImageView, fxid: "iconSecurity"},
                    {T: fxImageView, fxid: "iconProject"},
                    {T: fxImageView, fxid: "iconChart"},
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  },

  group: new Packages.javafx.scene.control.ToggleGroup(),
  selection: function (e) {
    var src = e.getSource();
    var name = src.getText();
    if (src.isSelected()) {
      importClass(Packages.javafx.scene.image.Image);
      var image = new Image("file:checkboxsample/" + name + ".png");
      this["icon" + name].setImage(image);
    } else {
      this["icon" + name].setImage(null);
    }
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main CheckboxSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-3 below should be displayed.

the CheckboxSample window
Figure-3. The Checkbox Sample window

ChoiceBox Sample

This section describes a the fxjs logo implementation of the Choice Box example. Copy the following code into a file called ChoiceBoxSample.js in the demo-directory.

{T: fxStage, title: "ChoiceBox Sample", width: 300, height: 200,
  scene: {T: fxScene, fill: fxALICEBLUE,
    root: {T: fxGroup,
      children: [
        {T: fxHBox, spacing: 30, alignment: fxCENTER, 
          padding: {T: fxInsets, top: 10, right: 0, bottom: 0, left: 10},
          children: [
            "this.cb" /* "hack" in "FXJS Language Guide" */,
            {T: fxLabel, fxid: "label", text: "Hello", width: 150, height: 30,
                style: "-fx-font: 25 arial;", layoutX: 40}
          ]
        }
      ]
    }
  },

  cb: new Packages.javafx.scene.control.ChoiceBox(
      Packages.javafx.collections.FXCollections.observableArrayList(
      "English", "Español", "Русский", "简体中文", "日本語")),

  greetings: ["Hello", "Hola", "Привет", "餵", "こんにちは"],

  main: function (args) {
    importClass(Packages.javafx.scene.control.Tooltip);
    importClass(Packages.javafx.beans.value.ChangeListener);
    this.cb.setTooltip(new Tooltip("Select the language"));
    this.cb.setValue("English");
    // Constructor of JavaScript change-listener ...
    var JSListener = function (aLabel, messages) {
      this.changed = function (ov, oldVal, newVal) {
        aLabel.setText(messages[newVal]);
      }
    }
    // Java ChangeListener instance ...
    var jListener = new ChangeListener(
        new JSListener(this.label, this.greetings));
    this.cb.getSelectionModel().selectedIndexProperty().
        addListener(jListener);
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main ChoiceBoxSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-4 below should be displayed.

the ChoiceBoxSample window
Figure-4. The ChoiceBox Sample window

Label Sample

This section describes a the fxjs logo implementation of the Label example. Before proceeding to run the example, verify that the demo-directory contains a directory named labelsample, and that labelsample contains a file named labels.jpg. Copy the following code into a file called LabelSample.js in the demo-directory.

{T: fxStage, title: "Label Sample", width: 400, height: 180,
  scene: {T: fxScene,
    root: {T: fxGroup,
      children: [
        {T: fxHBox, spacing: 10,
          children: [
            {T: fxLabel, text: "Search", font: {T: fxFont, name: "Arial", size: 30},
              textFill: {T: fxColor, web: "#0076a3"}, textAlignment: fxJUSTIFY,
              graphic: {T: fxImageView, 
              image: new Packages.javafx.scene.image.Image("file:labelsample/labels.jpg")} 
            },
            {T: fxLabel, text: "Values", font: {T: fxFont, name: "Cambria", size: 32},
              rotate: 270, translateY: 50 
            },
            {T: fxLabel, text: "A label that needs to be wrapped", fxid: "label3",
              wrapText: true, prefWidth: 100, translateY: 50, 
              onMouseEntered: function (e) {this.label3.setScaleX(1.5);},
              onMouseExited: function (e) {this.label3.setScaleX(1);},
            },
          ]
        }
      ]
    }
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main LabelSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the LabelSample window
Figure-??. The Label Sample window

LayoutSansTears Sample

This section describes a the fxjs logo implementation of the LayoutSansTears example. Before proceeding to run the example, you will need to copy out the files myStyles.css and logo.png from the article's attached zip file. Copy the following code into a file called LayoutSansTears.js in the demo-directory.

{T: fxStage, title: 'Layout Sans Tears: Solution', 
  scene: {T: fxScene, stylesheets: 'file:myStyles.css', width: 800, height: 500, 
    root: {T: fxBorderPane, 
      top: {T: fxHBox, fillHeight: true, 
        children: [
          {T: fxImageView, image: new Packages.javafx.scene.image.Image('file:logo.png')},
          {T: fxHBox, hgrow: Packages.javafx.scene.layout.Priority.ALWAYS},
          {T: fxLabel, id: 'app-title', text: 'App Title'},
          {T: fxHBox, hgrow: Packages.javafx.scene.layout.Priority.ALWAYS},
          {T: fxHBox, spacing: 5, margin: {T: fxInsets, top: 20, right: 10, bottom: 0, left: 0},
            children: [
              {T: fxTextArea, prefWidth: 120, prefHeight: 40, /*maxHeight: 
                  {T: fxRegion, Region: 'USE_PREF_SIZE'}*/}, 
              {T: fxButton, text: 'Go'}
            ]
          }
        ]
      }, // BorderPane.top
      center: {T: fxTabPane,
        tabs: [
          {T: fxTab, text: 'Tab A'}, 
          {T: fxTab, text: 'Tab B'}, 
          {T: fxTab, text: 'Tab C'} 
        ]
      }, // BorderPane.center
      bottom: {T: fxHBox, id: 'footer',
        children: [
          {T: fxLabel, text: 'Footer left'},
          {T: fxHBox, hgrow: Packages.javafx.scene.layout.Priority.ALWAYS},
          {T: fxLabel, text: 'Footer right'}
        ]
      }
    } // BorderPane
  }, // Scene
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main LayoutSansTears.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the LayoutSansTears window
Figure-??. The LayoutSansTears window

ListView Sample

This section describes a the fxjs logo implementation of the List View example. This example also uses a specialized Java implementation of ListCell. Copy the following code into a file called ListViewSample.js in the demo-directory.

{T: fxStage, title: "ListView Sample",
  scene: {T: fxScene, width: 200, height: 200,
    root: {T: fxVBox,
      children: [
        {T: fxListView, fxid: "list", cellFactory: "this.cellFactory", 
            vgrow: Packages.javafx.scene.layout.Priority.ALWAYS},
        {T: fxLabel, fxid: "label", font: {T: fxFont, name: "Verdana", size: 20}}
      ]
    }
  },

  cellFactory: new Packages.javafx.util.Callback(
      {call: function () {return new Packages.ColorRectCell();}}),

  data: Packages.javafx.collections.FXCollections.observableArrayList(
      "chocolate", "salmon", "gold", "coral", "darkorchid",
      "darkgoldenrod", "lightsalmon", "black", "rosybrown", "blue",
      "blueviolet", "brown"),

  main: function (arg) {
    importClass(Packages.javafx.scene.paint.Color);
    importClass(Packages.javafx.beans.value.ChangeListener);
    this.list.setItems(this.data);
    var CLConstructor = function (label) {
      this.changed = function (ov, oldValue, newValue) {
        label.setText(newValue);
        label.setTextFill(Color.web(newValue));
      }
    };
    var changeListener = new CLConstructor(this.label);
    this.list.getSelectionModel().selectedItemProperty().
        addListener(new ChangeListener(changeListener));
  }
}

Then copy the following Java code into the file ColorRectCell.java. Compile the file using the command "javac -cp ... ColorRectCell.java" (the ... must be replaced with the same classpath used under Prerequisite Step above).

import javafx.scene.control.ListCell;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;

public class ColorRectCell extends ListCell {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        Rectangle rect = new Rectangle(100, 20);
        if (item != null) {
            rect.setFill(Color.web(item));
            setGraphic(rect);
        } else {
            setGraphic(null);
        }
    }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main ListViewSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the ListViewSample window
Figure-??. The ListView Sample window

This section describes a the fxjs logo implementation of the Menu example. Before proceeding to run the example, verify that the demo-directory contains a directory named menusample, and that menusample contains a files named Apple.jpg, Hawthorn.jpg, Ivy.jpg, new.png, and Quince.jpg. Copy the following code into a file called MenuSample.js in the demo-directory.

{T: fxStage, title: "Menu Sample",
  scene: {T: fxScene, width: 400, height: 350, fill: fxOLDLACE,
    root: {T: fxVBox,
      children: [
        {T: fxMenuBar, 
          menus: [
            {T: fxMenu, text: 'File',
              items: [
                {T: fxMenuItem, text: "Shuffle",
                  graphic: {T: fxImageView, image: "this.imageNew"},
                  onAction: function (e) {
                    this.shuffle();
                    this.vbox.setVisible(true);
                  }
                },
                {T: fxMenuItem, text: "Clear",
                  accelerator: Packages.javafx.scene.input.KeyCombination.keyCombination("Ctrl+X"),
                  onAction: function (e) {
                    this.vbox.setVisible(false);
                  }
                },
                {T: fxSeparatorMenuItem},
                {T: fxMenuItem, text: "Exit",
                  onAction: function (e) {
                    Packages.java.lang.System.exit(0);
                  }
                }
              ]
            },
            {T: fxMenu, text: 'Edit',
              items: [
                {T: fxMenu, text: 'Picture Effect',
                  items: [
                    {T: fxRadioMenuItem, text: "Sepia Tone", toggleGroup: "this.groupEffect",
                      onAction: function (e) {
                        this.pic.setEffect(this.effects.sepia); 
                        this.noEffect.disable = false;
                      }
                    },
                    {T: fxRadioMenuItem, text: "Glow", toggleGroup: "this.groupEffect",
                      onAction: function (e) {
                        this.pic.setEffect(this.effects.glow);
                        this.noEffect.disable = false;
                      }
                     },
                    {T: fxRadioMenuItem, text: "Shadow", toggleGroup: "this.groupEffect",
                      onAction: function (e) {
                        this.pic.setEffect(this.effects.shadow);
                        this.noEffect.disable = false;
                      }
                    }
                  ]
                },
                {T: fxMenuItem, fxid: "noEffect", text: 'No Effect', disable: true, 
                  onAction: function (e) {
                    this.pic.setEffect(null);
                    e.getSource.disable = true;
                  }
                },
              ]},
            {T: fxMenu, text: 'View',
              items: [
                {T: fxCheckMenuItem, text: "Title", selected: true,
                  onAction: function (e) {this.name.setVisible(e.getSource().isSelected());}
                },
                {T: fxCheckMenuItem, text: "Binomial name", selected: true,
                  onAction: function (e) {this.binName.setVisible(e.getSource().isSelected());}
                },
                {T: fxCheckMenuItem, text: "Picture", selected: true,
                  onAction: function (e) {this.pic.setVisible(e.getSource().isSelected());}
                },
              ]}
          ]
        },
        {T: fxVBox, fxid: "vbox", alignment: fxCENTER, spacing: 10, 
          padding: {T: fxInsets, top: 0, right: 10, bottom: 0, left: 10},
          children: [
            {T: fxLabel, fxid: "name", font: {T: fxFont, name: "Verdana Bold", size: 22}},
            {T: fxLabel, fxid: "binName", font: {T: fxFont, name: "Arial Italic", size: 10}},
            {T: fxImageView, fxid: "pic", fitHeight: 150, preserveRatio: true},
            {T: fxLabel, fxid: "description", wrapText: true, textAlignment: fxJUSTIFY},
          ]
        }
      ]
    }
  },

  groupEffect: new Packages.javafx.scene.control.ToggleGroup(),

  effects: {
    sepia: new Packages.javafx.scene.effect.SepiaTone(),
    glow: new Packages.javafx.scene.effect.Glow(),
    shadow: new Packages.javafx.scene.effect.DropShadow()
  },

  imageNew: new Packages.javafx.scene.image.Image("file:menusample/new.png"),

  pages: [
    {name: "Apple", binName: "Malus domestica", 
      image: new Packages.javafx.scene.image.Image("file:menusample/Apple.jpg"),
      description: "The apple is the pomaceous fruit of the apple tree, species Malus"},
    {name: "Hawthorn", binName: "Crataegus monogyna", 
      image: new Packages.javafx.scene.image.Image("file:menusample/Hawthorn.jpg"),
      description: "The hawthorn is a large genus of shrubs and trees in the rose family,"},
    {name: "Ivy", binName: "Parthenocissus tricuspidata", 
      image: new Packages.javafx.scene.image.Image("file:menusample/Ivy.jpg"),
      description: "The ivy is a flowering plant in the grape family (Vitaceae) native to "},
    {name: "Quince", binName: "Cydonia oblonga", 
      image: new Packages.javafx.scene.image.Image("file:menusample/Quince.jpg"),
      description: "The quince is the sole member of the genus Cydonia and is native to "}
  ],

  currentIndex: -1,

  shuffle: function () {
    var i = this.currentIndex;
    while (i === this.currentIndex) {
      i = Math.floor(Math.random() * this.pages.length);
    }
    this.pic.setImage(this.pages[i].image);
    this.name.setText(this.pages[i].name);
    this.binName.setText("(" + this.pages[i].binName + ")");
    this.description.setText(this.pages[i].description);
    this.currentIndex = i;
  },

  main: function (arg) {
    this.shuffle();
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main MenuSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the MenuSample window
Figure-??. The MenuButton Sample window

RadioButton Sample

This section describes a the fxjs logo implementation of the Radio Button example. Copy the following code into a file called RadioButtonSample.js in the demo-directory.

{T: fxStage, title: "Radio Button Sample", width: 250, height: 150,
  scene: {T: fxScene,
    root: {T: fxGroup,
      children: [
        {T: fxHBox, spacing: 50, 
            padding: {T: fxInsets, top: 20, right: 10, bottom: 10, left: 20},
          children: [
            {T: fxVBox, spacing: 10,
              children: [
                {T: fxRadioButton, text: "Home", toggleGroup: "this.group", 
                    userData: "Home", onAction: function (e) {this.setIcon(e);}},
                {T: fxRadioButton, text: "Calendar", toggleGroup: "this.group",
                    userData: "Calendar", onAction: function (e) {this.setIcon(e);}},
                {T: fxRadioButton, text: "Contacts", toggleGroup: "this.group",
                    userData: "Contacts", onAction: function (e) {this.setIcon(e);}}
              ]
            },
            {T: fxImageView, fxid: "icon"}
          ]
        }
      ]
    }
  },

  group: new Packages.javafx.scene.control.ToggleGroup(),
  setIcon: function (e) {
    var rb = e.getSource();
    var path = "file:radiobuttonsample/" +
          rb.getUserData() + ".jpg";
    importClass(Packages.javafx.scene.image.Image);
    var image = new Image(path);
    this.icon.setImage(image);
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main RadioButtonSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the RadioButtonSample window
Figure-??. The RadioButton Sample window

ScrollBar Sample

This section describes a the fxjs logo implementation of the Scroll Bar example. Before proceeding to run the example, verify that the demo-directory contains a directory named scrollbarsample, and that scrollbarsample contains five files named fwN.jpg (with N = 1 .. 5). Copy the following code into a file called ScrollBarSample.js in the demo-directory.

{T: fxStage, title: "Scrollbar",
  scene: {T: fxScene, width: 180, height: 180, fill: fxBLACK, fxid: "scene",
    root: {T: fxGroup,
      children: [
        {T: fxVBox, fxid: "vb", layoutX: 5, spacing: 10},
        {T: fxScrollBar, fxid: "sc", min: 0, max: 360, prefHeight: 180,
          orientation: Packages.javafx.geometry.Orientation.VERTICAL}
      ]
    }
  },

  main: function (args) {
    importClass(Packages.javafx.beans.value.ChangeListener);
    importClass(Packages.javafx.scene.image.Image);
    importClass(Packages.javafx.scene.image.ImageView);
    this.sc.setLayoutX(this.scene.getWidth() - this.sc.getWidth());
    for (var i = 0; i < 5; i++) {
      var image = new Image("scrollbarsample/fw" + (i + 1) + ".jpg");
      var pic = new ImageView(image);
//      pic.setEffect(shadow);
      this.vb.getChildren().add(pic);
    }
    var vb = this.vb;
    var cl = {
      changed: function (ov, old_val, new_val) {vb.setLayoutY(-new_val);}
    }
    this.sc.valueProperty().addListener(new ChangeListener(cl)); 
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main ScrollBarSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the ScrollBarSample window
Figure-??. The ScrollBar Sample window

ToggleButton Sample

This section describes a the fxjs logo implementation of the Toggle Button example. Copy the following code into a file called ToggleButtonSample.js in the demo-directory.

{T: fxStage, title: "Toggle Button Sample", width: 250, height: 180,
  scene: {T: fxScene,
    root: {T: fxGroup,
      children: [
        {T: fxVBox, padding: {T: fxInsets, top: 20, right: 10, bottom: 10, left: 20},
          children: [
            {T: fxLabel, text: "Priority:"},
            {T: fxHBox, fxid: "hbox",
              children: [
                {T: fxToggleButton, text: "Minor", toggleGroup: "this.group",
                  style: "-fx-base: lightgreen;", 
                  onAction: function (e) {this.setColor(e);},
                  userData: Packages.javafx.scene.paint.Color.LIGHTGREEN},
                {T: fxToggleButton, text: "Major", toggleGroup: "this.group",
                  style: "-fx-base: lightblue;", 
                  onAction: function (e) {this.setColor(e);},
                  userData: Packages.javafx.scene.paint.Color.LIGHTBLUE},
                {T: fxToggleButton, text: "Critical", toggleGroup: "this.group",
                  style: "-fx-base: salmon;", 
                  onAction: function (e) {this.setColor(e);},
                  userData: Packages.javafx.scene.paint.Color.SALMON}
              ]
            },
            {T: fxRectangle, fxid: "rect", width: 145, height: 50, fill: fxWHITE, 
                stroke: fxDARKGRAY, strokeWidth: 2, arcHeight: 10, arcWidth: 10},
          ]
        }
      ]
    }
  },

  group: new Packages.javafx.scene.control.ToggleGroup(),
  setColor: function (e) {
    this.rect.setFill(e.getSource().getUserData());
  },
  main2: function (args) {
    this.rect.setWidth(this.hbox.getWidth());
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main ToggleButtonSample.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the ToggleButtonSample window
Figure-??. The ToggleButton Sample window

TreeView Sample

This section describes a the fxjs logo implementation of the Tree View example. The code is complex, and is therefore presented in steps. The organization used here follows the Original tutorial. Before proceeding to run the examples, verify that the demo-directory contains a directory named treeviewsample, and that treeviewsample contains files named department.png, folder_16.png, root.png.

Step-1 (Creating Tree Views)

Copy the following code into a file called TreeView1.js in the demo-directory.

{T: fxStage, title: 'Tree View Sample',
  scene: {T: fxScene, width: 300, height: 250,
    root: {T: fxStackPane,
      children: [
        {T: fxTreeView, showRoot: true,
          root: {T: fxTreeItem, value: 'Inbox', fxid: 'rootItem', 
              expanded: true, graphic: {T: fxImageView, image: "this.folderPng"}
          }
        }
      ] 
    }
  },

  folderPng: new Packages.javafx.scene.image.Image('file:treeviewsample/folder_16.png'),

  main: function(args) {
    var i;
    importClass(Packages.javafx.scene.control.TreeItem);
    for (i = 1; i < 6; ++i) {
      var item = new TreeItem("Message" + i);
      this.rootItem.getChildren().add(item);
    }
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main TreeView1.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the TreeSample1 window
Figure-??. The TreeView1 Sample window

Step-2 (Tree Items of Different Types)

Copy the following code into a file called TreeView2.js in the demo-directory.

{T: fxStage, title: 'Tree View Sample',
  scene: {T: fxScene, width: 300, height: 250,
    root: {T: fxStackPane,
      children: [
        {T: fxTreeView, showRoot: true,
          root: {T: fxTreeItem, value: 'Settings', fxid: 'rootItem', expanded: true,
              graphic: {T: fxImageView, 
              image: new Packages.javafx.scene.image.Image(
                  'file:treeviewsample/folder_16.png')},
            children: [
              {T: fxTreeItem, value: 'Security', fxid: 'securityItem', expanded: true},
              {T: fxTreeItem, value: 'Server', fxid: 'serverItem', expanded: true}
            ]
          }
        }
      ] 
    }
  },

  main: function(args) {
    var i;
    importPackage(Packages.javafx.scene.control);
    importPackage(Packages.javafx.scene.control);
    for (i = 1; i < 9; ++i) {
      var item = new TreeItem(new CheckBox("Option" + i));
      this.securityItem.getChildren().add(item);
    }
    for (i = 1; i < 5; ++i) {
      var item = new TreeItem(new RadioButton("Option" + i));
      this.serverItem.getChildren().add(item);
    }
  }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main TreeView2.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the TreeSample2 window
Figure-??. The TreeView2 Sample window

Step-3 (Cell Factories)

Copy the following code into a file called TreeView3.js in the demo-directory.

{T: fxStage, title: 'Tree View Sample',
  scene: {T: fxScene, width: 400, height: 300, fill: {T:'Color', value: 'LIGHTGRAY'},
    root: {T: fxVBox,
      children: [
        {T: fxTreeView, showRoot: true, 
          root: {T: fxTreeItem, value: 'MyCompany HR', fxid: 'rootNode', 
              expanded: true, graphic: {T: fxImageView, 
              image: new Packages.javafx.scene.image.Image(
                  'file:treeviewsample/root.png')}
          }
        }
      ] 
    }
  },

  main: function(args) {
    importClass(Packages.javafx.scene.control.TreeItem);
    importClass(Packages.javafx.scene.image.ImageView);
    var i;
    for (i = 0; i < this.employees.length; ++i) {
      var employee = this.employees[i];
      var empLeaf = new TreeItem(employee.getName());
      var found = false;
      var deptNames = this.rootNode.getChildren();
      var j;
      for (j = 0; j < deptNames.size(); ++j) {
        var depNode = deptNames.get(j);
        if (depNode.getValue().contentEquals(employee.getDepartment())) {
          depNode.getChildren().add(empLeaf);
          found = true;
          break;
        }
      }
      if (!found) {
        depNode = new TreeItem(employee.getDepartment(), new ImageView(this.depIcon));
        this.rootNode.getChildren().add(depNode);
        depNode.setExpanded(true);
        depNode.getChildren().add(empLeaf);
      }
    }
  },

  depIcon: new Packages.javafx.scene.image.Image(
      'file:treeviewsample/department.png'),

  employees: [
    new Packages.Employee("Ethan Williams", "Sales Department"),
    new Packages.Employee("Emma Jones", "Sales Department"),
    new Packages.Employee("Michael Brown", "Sales Department"),
    new Packages.Employee("Anna Black", "Sales Department"),
    new Packages.Employee("Rodger York", "Sales Department"),
    new Packages.Employee("Susan Collins", "Sales Department"),
    new Packages.Employee("Mike Graham", "IT Support"),
    new Packages.Employee("Judy Mayer", "IT Support"),
    new Packages.Employee("Gregory Smith", "IT Support"),
    new Packages.Employee("Jacob Smith", "Accounts Department"),
    new Packages.Employee("Isabella Johnson", "Accounts Department")
  ]
}

Then copy the following Java code into the file Employee.java. Compile the file using the command "javac -cp ... Employee.java" (the ... must be replaced with the same classpath used under Prerequisite Step above).

import javafx.beans.property.SimpleStringProperty;

public class Employee {
 
    private final SimpleStringProperty name;
    private final SimpleStringProperty department;
 
    public Employee(String name, String department) {
        this.name = new SimpleStringProperty(name);
        this.department = new SimpleStringProperty(department);
    }
 
    public String getName() {
        return name.get();
    }
 
    public void setName(String fName) {
        name.set(fName);
    }
 
    public String getDepartment() {
        return department.get();
    }
 
    public void setDepartment(String fName) {
        department.set(fName);
    }
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main TreeView3.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the TreeSample3 window
Figure-??. The TreeView3 Sample window

The code above (TreeView3.js + Employee.java) is a good model for situations that mandate data sources in Java objects. But if that is not a requirement, a pure-JavaScript solution may be more suitable. The following module consits of just one JavaScript file containing all the elements of the application. The Employee data is held in an array of JavaScript objects instead of Java objects

{T: fxStage, title: 'Tree View Sample',
  scene: {T: fxScene, width: 400, height: 300, fill: {T:'Color', value: 'LIGHTGRAY'},
    root: {T: fxVBox,
      children: [
        {T: fxTreeView, showRoot: true, 
          root: {T: fxTreeItem, value: 'MyCompany HR', fxid: 'rootNode', 
              expanded: true, graphic: {T: fxImageView, 
              image: new Packages.javafx.scene.image.Image(
                  'file:treeviewsample/root.png')}
          }
        }
      ] 
    }
  },

  main: function (args) {
    importClass(Packages.javafx.scene.control.TreeItem);
    importClass(Packages.javafx.scene.image.ImageView);
    var i;
    for (i = 0; i < this.employees.length; ++i) {
      var employee = this.employees[i];
      var empLeaf = new TreeItem(employee.name /*getName()*/);
      var found = false;
      var deptNames = this.rootNode.getChildren();
      var j;
      for (j = 0; j < deptNames.size(); ++j) {
        var depNode = deptNames.get(j);
        if (depNode.getValue().contentEquals(employee.department /*getDepartment()*/)) {
          depNode.getChildren().add(empLeaf);
          found = true;
          break;
        }
      }
      if (!found) {
        depNode = new TreeItem(employee.department /*getDepartment()*/, new ImageView(this.depIcon));
        this.rootNode.getChildren().add(depNode);
        depNode.setExpanded(true);
        depNode.getChildren().add(empLeaf);
      }
    }
  },

  depIcon: new Packages.javafx.scene.image.Image(
      'file:treeviewsample/department.png'),

  employees: [
    {name: "Ethan Williams", department: "Sales Department"},
    {name: "Emma Jones", department: "Sales Department"},
    {name: "Michael Brown", department: "Sales Department"},
    {name: "Anna Black", department: "Sales Department"},
    {name: "Rodger York", department: "Sales Department"},
    {name: "Susan Collins", department: "Sales Department"},
    {name: "Mike Graham", department: "IT Support"},
    {name: "Judy Mayer", department: "IT Support"},
    {name: "Gregory Smith", department: "IT Support"},
    {name: "Jacob Smith", department: "Accounts Department"},
    {name: "Isabella Johnson", department: "Accounts Department"}
  ]
}

The next step adds a custom TreeCell to enable employee names to be edited. The code uses a the fxjs logo pure-JavaScript mechanism for overriding base class methods. The original example's code Example 14-4 Implementing a Cell Factory required the creation of a derived class of TreeCell. The code below achieves the same effect by creating a new instance of fxjs.TreeCell (a the fxjs logo-provided class) and passing to its constructor a JavaScript object containing the definitions of the overriding methods. The JavaScript object with the specializing methods is produced by calling the constructor function ConstrTreeCell().

Copy the following code into a file called TreeView3a.js in the demo-directory.

{T: fxStage, title: 'Tree View Sample',
  scene: {T: fxScene, width: 400, height: 300, fill: {T:'Color', value: 'LIGHTGRAY'},
    root: {T: fxVBox,
      children: [
        {T: fxTreeView, showRoot: true, editable: true,
          cellFactory: "this.getCellFactory()",
          root: {T: fxTreeItem, value: 'MyCompany HR', fxid: 'rootNode', 
              expanded: true, graphic: {T: fxImageView, 
              image: new Packages.javafx.scene.image.Image(
                  'file:treeviewsample/root.png')}
          }
        }
      ] 
    }
  },

//
// Constructor function for a 'TreeCell' object
//
  ConstrTreeCell: function () {
    this.startEdit = function (base) {
      if (textField === null) {
        createTextField(base);
      }
      base.setText(null);
      base.setGraphic(textField);
      textField.selectAll();
    };

    this.cancelEdit = function (base) {
      base.setText(base.getItem());
      base.setGraphic(base.getTreeItem().getGraphic());
    };

    this.updateItem = function (base, item, empty) {
      if (empty) {
        base.setText(null);
        base.setGraphic(null);
      } else {
        if (base.isEditing()) {
          if (textField !== null) {
            textField.setText(getString(base));
          }
          base.setText(null);
          base.setGraphic(textField);
        } else {
          base.setText(getString(base));
          base.setGraphic(base.getTreeItem().getGraphic());
        }
      }
    };

    this.commitEdit = function (base, newValue) {
    // Does nothing, but function declaration required
    };

    var textField = null;

    var getString = function (base) {
      return base.getItem() === null ? "" : base.getItem().toString();
    }

    var createTextField = function (base) {
      importClass(Packages.javafx.scene.input.KeyCode);
      importClass(Packages.javafx.scene.control.TextField);
      importClass(Packages.javafx.event.EventHandler);
      textField = new TextField(getString(base));
      var that = this;
      var handler = {handle: function (keyEvent) {
        if (keyEvent.getCode() === KeyCode.ENTER) {
          base.commitEdit(textField.getText());
        } else if (keyEvent.getCode() === KeyCode.ESCAPE) {
          that.cancelEdit();
        }
      }};
      textField.setOnKeyReleased(new EventHandler(handler));
    };
  },

//
// Creates CellFactory using 'TreeCell' object
//
  getCellFactory: function () {
    importClass(Packages.fxjs.TreeCell);
    importClass(Packages.javafx.util.Callback);
    var CTC = this.ConstrTreeCell;
    var caller = {call: function () {
        var tc = new TreeCell(new CTC());
        return tc;}};
    return new Callback(caller);
  },

  main: function (args) {
    importClass(Packages.javafx.scene.control.TreeItem);
    importClass(Packages.javafx.scene.image.ImageView);
    var i;
    for (i = 0; i < this.employees.length; ++i) {
      var employee = this.employees[i];
      var empLeaf = new TreeItem(employee.name);
      var found = false;
      var deptNames = this.rootNode.getChildren();
      var j;
      for (j = 0; j < deptNames.size(); ++j) {
        var depNode = deptNames.get(j);
        if (depNode.getValue().contentEquals(employee.department)) {
          depNode.getChildren().add(empLeaf);
          found = true;
          break;
        }
      }
      if (!found) {
        depNode = new TreeItem(employee.department, new ImageView(this.depIcon));
        this.rootNode.getChildren().add(depNode);
        depNode.setExpanded(true);
        depNode.getChildren().add(empLeaf);
      }
    }
  },

  depIcon: new Packages.javafx.scene.image.Image(
      'file:treeviewsample/department.png'),

  employees: [
    {name: "Ethan Williams", department: "Sales Department"},
    {name: "Emma Jones", department: "Sales Department"},
    {name: "Michael Brown", department: "Sales Department"},
    {name: "Anna Black", department: "Sales Department"},
    {name: "Rodger York", department: "Sales Department"},
    {name: "Susan Collins", department: "Sales Department"},
    {name: "Mike Graham", department: "IT Support"},
    {name: "Judy Mayer", department: "IT Support"},
    {name: "Gregory Smith", department: "IT Support"},
    {name: "Jacob Smith", department: "Accounts Department"},
    {name: "Isabella Johnson", department: "Accounts Department"}
  ]
}

Run the following command in the demo-directory: "java -cp ... fxjs.Main TreeView3a.js" (the ... must be replaced with the information used under Prerequisite Step above). The JavaFX window shown in Figure-?? below should be displayed.

the TreeSample3a window
Figure-??. The TreeView3a Sample window

Step-4 (New Tree Items)

Coming soon!

UIControlSamples.zip - License.txt

/*
 * Copyright (c) 2012 Oracle and/or its affiliates.
 * All rights reserved. Use is subject to license terms.
 *
 * This file is available and licensed under the following license:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  - Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the distribution.
 *  - Neither the name of Oracle nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
 
Close
loading
Please Confirm
Close