有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java让窗口在JavaFX中向下滚动

所以我现在学习Java,因为我知道JavaScript和PHP。我正在使用JavaFX在Netbeans中工作,我正在尝试创建一个创建5个按钮的程序。(这是在创建新的JavaFX应用程序时修改Netbeans附带的代码。)如果我将场景的y参数更改为小于所有按钮的y参数,它将不会显示其余按钮,并且无法向下滚动。这就是我目前所拥有的。如何使其向下滚动以便可以看到所有按钮?我知道我可以将场景更改回原来的高度,但我想学习如何使用JavaFX滚动

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javax.swing.JScrollPane;

public class JavaFXApplication1 extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        Button[] btn=new Button[5];
        for(int i=0;i<5;i++){
            btn[i] = new Button();
            btn[i].setText(i+"");
            GridPane.setRowIndex(btn[i],i); 
            root.getChildren().addAll(btn[i]);
            btn[i].setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("This is a button");
            }
        });

        }

        Scene scene = new Scene(root, 300, 50);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


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

}

共 (1) 个答案

  1. # 1 楼答案

    使用ScrollPane将根目录设置为:

    ScrollPane sp = new ScrollPane();
    sp.setContent(root);
    
    Scene scene = new Scene(sp, 300, 50);