Saturday, 23 June 2018

JavaFX: Slider: Add event handling to slider widget

By adding a listener to slider widget, you can listen the events on slider widget.

slider.valueProperty().addListener((ObservableValue<? extends Number> ov, Number old_val, Number new_val) -> {
         label.setText("Slider changed from " + old_val + " to " + new_val);
});

Find the below working application.

SliderApp.java
package com.sample.demos;

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class SliderApp extends Application {

 @Override
 public void start(Stage primaryStage) throws Exception {
  Slider slider = new Slider();
  slider.setShowTickLabels(true);
  slider.setShowTickMarks(true);
  slider.setMin(0);
  slider.setMax(100);
  slider.setValue(50);
  slider.setMajorTickUnit(20);
  slider.setMinorTickCount(5);
  slider.setBlockIncrement(10);
  slider.setMinWidth(400);

  Label label = new Label();

  slider.valueProperty().addListener((ObservableValue<? extends Number> ov, Number old_val, Number new_val) -> {
   label.setText("Slider changed from " + old_val + " to " + new_val);
  });

  HBox hBox = new HBox(50, slider, label);

  Scene scene = new Scene(hBox);

  primaryStage.setScene(scene);

  primaryStage.setTitle("Slider widget Example");
  primaryStage.setWidth(900);
  primaryStage.setHeight(500);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

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




Previous                                                 Next                                                 Home

No comments:

Post a Comment