我想调整ScrollPane的大小以适应父组件。我测试了这段代码:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
BorderPane bp = new BorderPane();
bp.setPrefSize(600, 600);
bp.setMaxSize(600, 600);
bp.setStyle("-fx-background-color: #2f4f4f;");
VBox vb = new VBox(bp);
ScrollPane scrollPane = new ScrollPane(vb);
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
Scene scene = new Scene(scrollPane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
但是你可以看到我没有看到树滚动条。我的代码有什么问题吗?
答案 0 :(得分:4)
滚动条不会显示,因为
ScrollBarPolicy.AS_NEEDED
要解决此问题,您可以删除setFitToHeight
和setFitToWidth
并将其保留为false。
请注意,ScrollBarPolicy
也可以设置为ALWAYS
而不是AS_NEEDED
,即使窗口展开也会保留滚动条。
Refer here for more information using ScrollPane
ScrollPane API: setFitToHeight
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
BorderPane bp = new BorderPane();
bp.setPrefSize(600, 600);
bp.setMaxSize(600, 600);
bp.setStyle("-fx-background-color: #2f4f4f;");
VBox vb = new VBox(bp);
ScrollPane scrollPane = new ScrollPane(vb);
//scrollPane.setFitToHeight(true);
//scrollPane.setFitToWidth(true);
scrollPane.setHbarPolicy(ScrollBarPolicy.ALWAYS);
scrollPane.setVbarPolicy(ScrollBarPolicy.ALWAYS);
Scene scene = new Scene(scrollPane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}