JavaFX ScrollBar handle change event

Description

JavaFX ScrollBar handle change event

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;

public class Main extends Application {
  @Override/*from w w w.j a v a  2s . com*/
  public void start(Stage primaryStage) {
    Text text = new Text(20, 20, "JavaFX Programming");
    
    ScrollBar sbHorizontal = new ScrollBar();
    ScrollBar sbVertical = new ScrollBar();
    sbVertical.setOrientation(Orientation.VERTICAL);
    
    // Create a text in a pane
    Pane paneForText = new Pane();
    paneForText.getChildren().add(text);
    
    // Create a border pane to hold text and scroll bars
    BorderPane pane = new BorderPane();
    pane.setCenter(paneForText);
    pane.setBottom(sbHorizontal);
    pane.setRight(sbVertical);

    // Listener for horizontal scroll bar value change
    sbHorizontal.valueProperty().addListener(ov -> 
      text.setX(sbHorizontal.getValue() * paneForText.getWidth() /
        sbHorizontal.getMax()));
    
    // Listener for vertical scroll bar value change
    sbVertical.valueProperty().addListener(ov -> 
      text.setY(sbVertical.getValue() * paneForText.getHeight() /
        sbVertical.getMax()));
    

    Scene scene = new Scene(pane, 450, 170);
    primaryStage.setTitle("ScrollBarDemo");
    primaryStage.setScene(scene);
    primaryStage.show();
  }


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



PreviousNext

Related