如何使用 JavaFX 建立滾動窗格?


滾動窗格包含一個 UI 元素,並提供一個該元素的可滾動檢視。在 JavaFX 中,可以透過例項化 javafx.scene.control.ScrollPane 類來建立滾動窗格。可以使用 setContent() 方法設定滾動窗格的內容。

  • 將滾動窗格新增到節點的方式 −

  • 例項化 ScrollPane 類。

  • 建立所需的節點。

  • 使用 setContent() 方法將節點設定到滾動窗格。

  • 使用設定器方法設定滾動窗格的尺寸。

  • 將滾動窗格新增到佈局窗格或組。

示例

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ScrollPaneActionExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //creating the image object
      InputStream stream = new FileInputStream("D:\images\elephant.jpg");
      Image image = new Image(stream);
      //Creating the image view
      ImageView imageView = new ImageView();
      //Setting image to the image view
      imageView.setImage(image);
      //Setting the image view parameters
      imageView.setX(5);
      imageView.setY(0);
      imageView.setFitWidth(595);
      imageView.setPreserveRatio(true);
      //Creating the scroll pane
      ScrollPane scroll = new ScrollPane();
      scroll.setPrefSize(595, 200);
      //Setting content to the scroll pane
      scroll.setContent(imageView);
      //Setting the stage
      Group root = new Group();
      root.getChildren().addAll(scroll);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Scroll Pane Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於: 18-May-2020

4 千次 + 檢視

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.