Welcome!

Machine Learning Authors: William Schmarzo, Elizabeth White, Jnan Dash, Pat Romanski, Liz McMillan

Related Topics: Java IoT, Industrial IoT, Linux Containers, Open Source Cloud, Machine Learning , Agile Computing

Java IoT: Blog Feed Post

JavaFX Event Handling and Property Binding

In JavaFX an event object is represented by the instance of the class javafx.event.Event

The event handler for the button Sign In will be implemented using an anonymous inner class. The event handler for the Cancel button will be implemented using a lambda expression. I’ll implement the click handler for the hyperlink Forgot password using a method reference. The code of the class GridPaneSampleEvents is shown next (see the section marked as event handlers).

public class GridPaneSampleEvents extends Application {

    public void start(Stage primaryStage) {
        
        Label userIdLbl = new Label("User ID:");
        TextField userIdTxt = new TextField();
        Label userPwdLbl = new Label("Password:");
        PasswordField userPwdTxt = new PasswordField();
        Button signInBtn = new Button ("Sign In");
        Button cancelBtn = new Button ("Cancel");
        Hyperlink forgotPwdLink = new Hyperlink("Forgot password");

        GridPane root = new GridPane();
        root.setVgap(20);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);
        
        // Using static methods for setting node constraints 
        GridPane.setConstraints(userIdLbl, 0, 0);
        GridPane.setConstraints(userIdTxt, 1, 0);
        GridPane.setConstraints(userPwdLbl, 0, 1);
        GridPane.setConstraints(userPwdTxt, 1, 1);
        GridPane.setConstraints(signInBtn, 0, 2);
        //Cancel button: span 1, right aligned
        GridPane.setConstraints(cancelBtn, 1,2, 1, 1, HPos.RIGHT,
                                                      VPos.CENTER);
        GridPane.setConstraints(forgotPwdLink, 0, 3,2,1);

        root.getChildren().addAll(userIdLbl, userIdTxt, userPwdLbl, 
                     userPwdTxt,signInBtn, cancelBtn, forgotPwdLink);
            
        // event handlers
        //1. Anonymous class 
        signInBtn.setOnAction(new EventHandler(){
            public void handle(ActionEvent evt){
              System.out.println(
                      "Anonymous class handler. Sign in clicked.");   
            }
        });
        
        // lambda expression
        cancelBtn.setOnAction(evt -> 
            System.out.println("Lambda handler. Cancel clicked.")
        );
        
        // method reference
        forgotPwdLink.setOnAction(this::forgotPwdHandler);
        
        // Show the window
        Scene scene = new Scene(root,250,200);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
    
    private void forgotPwdHandler(ActionEvent evt){
        System.out.println(
              "Method reference handler. Forgot password clicked");
    }

    public static void main(String[] args) {
        launch(args);
    }
}

If you run this program, and click on Sign In, Cancel, and Forgot password, the console output will show the following:

Anonymous class handler. Sign in clicked.
Lambda handler. Cancel clicked.
Method reference handler. Forgot password clicked

While each of the event handlers works the same, I prefer the lambda expression version as it’s concise and is easy to read. Each of the JavaFX GUI controls has a set of setOnXXX() methods (e.g. setOnAction(), setOnMouseMoved() et al) that should be called for the events you’re interested in handling.

Properties and Binding
While Java developers casually use the words properties referring to class attributes, JavaFX properties are more than just class attributes. JavaFX defines an interface javafx.beans.property.Property, which has a very useful functionality allowing to bind the GUI components (the view) with properties of the Java classes (the model) and automate notifications of the GUI components when the value in the model change or visa versa.

Imagine that you’re developing a financial application that receives notification from the server about the stock price changes. When a Java object receives the new price, you need to modify the content of the corresponding GUI component. With JavaFX you can simply bind a property price of a Java class to the property of, say Label component. No more coding required. As soon as the price value changes, the Label will be automatically updated. JavaFX properties greatly simplify the process of synchronization of the data and the GUI.

Existing implementations of the Property interface serve as wrappers to Java attributes adding the change notification functionality. The interface Property declares the following methods: bind(), unbind(), bindBidirectional() , unbindBidirctional(), and isBound(). Can you bind any value to a JavaFX property? No – the value has to be of an ObservableValue type.

JavaFx property classes are located in the package javafx.beans.property. For each property type there are two classes: read-only and read-write ones. For example, if you need a String property, use either SimpleStringProperty or ReadOnlyStringWrapper. Both of these implement StringProperty interface. Similarly named classes exist for other data types and some collections too.

Let’s modify the GridPaneSampleEvents class. I will place an additional Label components at the bottom of the Sign In window. It’ll display the messages about the events as the user clicks on the buttons and the hyperlink. Initially this label will not have any text:

Label messageLbl = new Label();

JavaFX properties are observables. Hence we can add a listener (observer) to the property to be notified when the property value changes. But it’s much easier to simply use property in a binding expressions. I’ll bind this label to the string property, and as soon as the value of this property changes, the label component messageLbl will display this value.

private StringProperty message = new SimpleStringProperty();
messageLbl.textProperty().bind(message);

The class GridePaneSampleEvents was just printing messages on the system console when the user clicked on the buttons or the hyperlink. The new class GridPaneSampleBinding will modify our property message instead, for example:

cancelBtn.setOnAction(evt -> message.set(“Cancel clicked.”));

The click on the cancelBtn changes the value of the the message property, which was bound to the label’s text – the GUI will change automatically! This is how our Sign In window will look like after pressing the Cancel button.

f1808

The complete code of the GridPaneSampleBinding class is shown next.

public class GridPaneSampleBinding extends Application {

    //Declaring a JavaFX property
    private StringProperty message = new SimpleStringProperty();
    
    public void start(Stage primaryStage) {
        
        Label userIdLbl = new Label("User ID:");
        TextField userIdTxt = new TextField();
        Label userPwdLbl = new Label("Password:");
        PasswordField userPwdTxt = new PasswordField();
        Button signInBtn = new Button ("Sign In");
        Button cancelBtn = new Button ("Cancel");
        Hyperlink forgotPwdLink = new Hyperlink("Forgot password");
        
        // A label to display messages using binding
        Label messageLbl = new Label();
        // binding the StringProperty to a GUI component
        messageLbl.textProperty().bind(message);
        
        GridPane root = new GridPane();
        root.setVgap(20);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);
        
        // Using static methods for setting node constraints 
        GridPane.setConstraints(userIdLbl, 0, 0);
        GridPane.setConstraints(userIdTxt, 1, 0);
        GridPane.setConstraints(userPwdLbl, 0, 1);
        GridPane.setConstraints(userPwdTxt, 1, 1);
        GridPane.setConstraints(signInBtn, 0, 2);
        
        //Cancel button: span 1, right aligned
        GridPane.setConstraints(cancelBtn, 1,2, 1, 1, 
                                      HPos.RIGHT, VPos.CENTER);
        GridPane.setConstraints(forgotPwdLink, 0, 3,2,1);
        
        // Message label: span 2
        GridPane.setConstraints(messageLbl, 0,4,2,1);

        root.getChildren().addAll(userIdLbl, userIdTxt, userPwdLbl,
          userPwdTxt,signInBtn, cancelBtn, forgotPwdLink, messageLbl);
        
        // event handlers
        //1. Anonymous class 
        signInBtn.setOnAction(new EventHandler(){
            public void handle(ActionEvent evt){
                  message.set("Sign in clicked.");   
            }
        });
        
        // lambda expression
        cancelBtn.setOnAction(evt -> 
           message.set("Cancel clicked.")
        );
        
        // method reference
        forgotPwdLink.setOnAction(this::forgotPwdHandler);
        
        // Show the window
        Scene scene = new Scene(root,250,220);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private void forgotPwdHandler(ActionEvent evt){
        message.set("Forgot password clicked");
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The binding can be bidirectional. If the value of the GUI component changes it can change the value of the underlying model (remember MVC?), and if the value of the model changes the GUI is updated too. If you want to stop binding at any time, use the method unbind().

That’s all folks for now.

Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

@CloudExpo Stories
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"ZeroStack is a startup in Silicon Valley. We're solving a very interesting problem around bringing public cloud convenience with private cloud control for enterprises and mid-size companies," explained Kamesh Pemmaraju, VP of Product Management at ZeroStack, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Enterprises are adopting Kubernetes to accelerate the development and the delivery of cloud-native applications. However, sharing a Kubernetes cluster between members of the same team can be challenging. And, sharing clusters across multiple teams is even harder. Kubernetes offers several constructs to help implement segmentation and isolation. However, these primitives can be complex to understand and apply. As a result, it’s becoming common for enterprises to end up with several clusters. Thi...
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"Infoblox does DNS, DHCP and IP address management for not only enterprise networks but cloud networks as well. Customers are looking for a single platform that can extend not only in their private enterprise environment but private cloud, public cloud, tracking all the IP space and everything that is going on in that environment," explained Steve Salo, Principal Systems Engineer at Infoblox, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventio...
"Codigm is based on the cloud and we are here to explore marketing opportunities in America. Our mission is to make an ecosystem of the SW environment that anyone can understand, learn, teach, and develop the SW on the cloud," explained Sung Tae Ryu, CEO of Codigm, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, provided a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to oper...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, discussed how by using ne...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored applications in several industries and discussed technologies that allow the deployment of advanced visualization solutions to the cloud.
Vulnerability management is vital for large companies that need to secure containers across thousands of hosts, but many struggle to understand how exposed they are when they discover a new high security vulnerability. In his session at 21st Cloud Expo, John Morello, CTO of Twistlock, addressed this pressing concern by introducing the concept of the “Vulnerability Risk Tree API,” which brings all the data together in a simple REST endpoint, allowing companies to easily grasp the severity of the ...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, discussed how data centers of the future will be managed, how the p...
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"We're focused on how to get some of the attributes that you would expect from an Amazon, Azure, Google, and doing that on-prem. We believe today that you can actually get those types of things done with certain architectures available in the market today," explained Steve Conner, VP of Sales at Cloudistics, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.