我正在用ScrollPane編寫GUI應用程序,但在調整大小時遇到了一些問題。我提取在下面的示例中的基本代碼:JavaFX ScrollPane [setPrefSize,setMinSize,setMaxSize]不起作用
import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;
import javafx.scene.control.ScrollPane;
public class JavaFXExample extends Application {
final int width = 300;
final int height = 300;
@Override
public void start(Stage primaryStage) {
Button b = new Button("This should be at the bottom!");
//this vbox goes inside the scrollpane
VBox boxInScrollPane = new VBox(10);
boxInScrollPane.setAlignment(Pos.BOTTOM_CENTER);
boxInScrollPane.getChildren().add(b);
//main content
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(boxInScrollPane);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
//Doesn't do anything!
scrollPane.setPrefSize(100, 100);
scrollPane.setMaxSize(100, 100);
scrollPane.setMinSize(100, 100);
Scene scene = new Scene(scrollPane, width, height);
primaryStage.setScene(scene);
primaryStage.show();
//set size of boxInScrollPane to be equal to the viewport
Bounds viewportBounds = scrollPane.getViewportBounds();
double innerWidth = viewportBounds.getMaxX() - viewportBounds.getMinX();
double innerHeight = viewportBounds.getMaxY() - viewportBounds.getMinY();
System.out.println(innerWidth + " " + innerHeight);
boxInScrollPane.setPrefSize(innerWidth, innerHeight);
}
public static void main(String[] args) {
launch(args);
}
}
所以我有一個窗口,其中包含一個ScrollPane,其中包含一個垂直框,其中包含一個按鈕。這裏的例子中,我調整了一個300x300px窗口中的滾動窗格大小爲100x100px,是任意的。重要的是,當我運行這段代碼時,我會看到一個可以填滿整個窗口的滾動窗格!這裏是我的輸出:
這是怎麼回事?