Saturday 2 June 2018

JavaFX: CheckBox: Event handling

By adding a change listener to checkbox, you can keep track of checkbox state changes.

Ex
checkBox.selectedProperty().addListener((ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {
         System.out.println(checkBox.getText() + " changed from " + old_val + " to " + new_val);
});

Find the below working application.

CheckBoxApp.java
package com.sample.demos;

import java.io.FileNotFoundException;
import java.net.MalformedURLException;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class CheckBoxApp extends Application {

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {
  CheckBox checkBox1 = new CheckBox("Chess");
  CheckBox checkBox2 = new CheckBox("Cricket");

  CheckBox[] checkBoxes = { checkBox1, checkBox2 };

  for (CheckBox checkBox : checkBoxes) {
   checkBox.selectedProperty()
     .addListener((ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {
      System.out.println(checkBox.getText() + " changed from " + old_val + " to " + new_val);
     });
  }

  VBox vbox = new VBox(10, checkBox1, checkBox2);

  Scene scene = new Scene(vbox, 400, 300);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX CheckBox Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

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




Try to select and unselect the checkboxes, you can able to see below kind of messages in console.

Cricket changed from false to true
Cricket changed from true to false
Chess changed from false to true
Chess changed from true to false





Previous                                                 Next                                                 Home

No comments:

Post a Comment