Channels ▼
RSS

JVM Languages

JavaFX Custom Controls


Using the Control

For illistration purposes, our sample application will be kept very simple. Listing 4 contains the complete JavaFX Script code that opens a window with two components in it.


package customlist;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.text.Font;
import javafx.stage.Alert;

function run() {
    var list : CustomList;
    var items : ListItem[];
    
    Stage {
        title: "Application title"
        scene: Scene {
            width: 640
            height: 480
            content: [
                Button {
                    layoutX: 10;
                    layoutY: 2;
                    text: "Get Selected"
                    action: function() {
                      var items: ListItem[] = 
                          list.getSelected();
                      var txt: String = 
                          "Lines selected: {items.size()}";
                      for ( item in items ) {
                          txt = txt.concat("\n")
                            .concat("Item {item.position}")
                            .concat(" selected.")
                            .concat(" Text: {item.text}");
                      }
                      Alert.inform(txt);
                    }
                },
                list = CustomList {
                    layoutX: 10;
                    layoutY: 30;
                    width: 400;
                    height: 400;
                    font: Font { name: "dialog" size: 12 }
                    items: [ 
                        for ( x in [0..100] ) {
                            ListItem { text: "Line {x}" } 
                        }
                    ];
                },
            ]
        }
    }
}

Listing 4

A button with the text "Get Selected", and an instance of the multi-select list view control just below it. The Stage represents the main window of the application, and the Scene contains the content of the window:


Stage {
        title: "Multi-select Test"
        scene: Scene {
            width: 640
            height: 480
            content: [
                Button {
                    // ...
                },
                list = CustomList {
                    layoutX: 10;
                    layoutY: 30;
                    width: 400;
                    height: 400;
                    font: Font { name: "dialog" size: 12 }
                    items: [ for ( x in [0..100] ) {
                        ListItem { text: "Line {x}" }
                        }
                    ];
                },
            ]
        }
    }

This code focuses on the CustomList control (some other code has been removed for now). First, the control's position and size properties are set like any other control. Next, the default font is overriden, and set to 12-point "dialog". Next, the items are set as a property with a for loop that creates 100 ListItem objects with the text "Line 1", "Line 2", and so on. And that's it!

When executed, select a few items in the list, and then click the "Get Selected" button, the button's action function executes the following code:


action: function() {
        var items: ListItem[] = list.getSelected();
        var txt: String = "Lines selected: {items.size()}";
        for ( item in items ) {
            txt = txt.concat("\n")
              .concat("Item {item.position}")
              .concat(" selected.")
              .concat(" Text: {item.text}");
        }
        Alert.inform(txt);
    }

The resulting array from the call to list.getSelected is parsed, and used in the for loop. As a result, an alert dialog box will appear that displays the number of items selected within the list, and their individual pieces of text, as in Figure 3.

[Click image to view at full size]
Figure 3: The multi-select custom list view sample application with selections.

In this example, we had set the items property of the control when we declared the control within the Scene. As an alternative, you can set the text in the control within your code by calling list.setItems directly, with a populated array of ListItem objects, such as:


    var items : ListItem[];
    items = [ {
            for ( x in [0..100] ) {
                ListItem { text: "Line {x}" }
            }
        }
    ];
    list.setItems( items );

Alternatively, you can initialize the array at declaration time, as in the following:


    var items : ListItem[] = [   
          ListItem { text: "Line 1"},
          ListItem { text: "Line 2"},
          ListItem { text: "Line 3"}
          ListItem { text: "Line 4"}
          ListItem { text: "Line 5"}
          ListItem { text: "Line 6"}
    ];
    list.setItems( items );

Any of these approaches are valid; it comes down to convenience and a matter of taste in most cases.

Conclusion

This article has shown how straightforward it is to create custom controls in JavaFX, and how little code it takes to build customized components that suit your needs. Through the power and simplicity of JavaFX Script, as well as leveraging the set of existing controls, components, and classes within the JavaFX API, you can tailor your application's UI and behavior quickly and easily.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video