Wednesday, February 15, 2012

JavaFX 2.0: Implement ChangeListener for Slider

JavaFX 2.0: Implement ChangeListener for Slider
package javafx_uislider;

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

/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFX_uiSlider extends Application {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("http://java-buddy.blogspot.com/");

VBox root = new VBox();

Slider mySlider = new Slider();
mySlider.setMin(0);
mySlider.setMax(100);
mySlider.setValue(50);
mySlider.setShowTickLabels(true);
mySlider.setShowTickMarks(true);
mySlider.setMajorTickUnit(50);
mySlider.setMinorTickCount(5);
mySlider.setBlockIncrement(10);

final Label mySliderValue = new Label(Double.toString(mySlider.getValue()));

mySlider.valueProperty().addListener(new ChangeListener<Number>() {

@Override
public void changed(ObservableValue<? extends Number> arg0,
Number arg1, Number arg2) {
mySliderValue.setText(String.format("%.1f", arg2)); //new value
}

});

root.getChildren().add(mySlider);
root.getChildren().add(mySliderValue);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}

No comments:

Post a Comment