代码之家  ›  专栏  ›  技术社区  ›  parsecer

JavaFX,GridPane:使GridPane的列中的元素具有所有列宽

  •  1
  • parsecer  · 技术社区  · 2 年前
    public class Tester extends Application  {
        private static final int WIDTH = 300;
        private static final int HEIGHT = 400;
    
        @Override
        public void start(Stage stage) {
            GridPane pane = new GridPane();
            pane.setAlignment(Pos.TOP_LEFT);
            pane.setHgap(10);
            pane.setVgap(10);
            pane.setPadding(new Insets(10, 10, 10, 10));
    
            pane.add(new Button("cat"), 0, 0);
            pane.add(new Button("monkey"), 0, 1);
            pane.add(new Button("elephant and lion"), 0, 2);
    
            Scene scene = new Scene(pane, WIDTH, HEIGHT);
            stage.setScene(scene);
            stage.show();
        }
    }
    

    显示:

    enter image description here

    如何使所有按钮都具有相同的宽度,如下所示:

    enter image description here

    我试着将按钮添加到 VBox 然后添加 VBox GridPane ,但没有起作用。

    1 回复  |  直到 2 年前
        1
  •  3
  •   Sai Dandem    2 年前

    在这种情况下,您需要将按钮的最大宽度设置为POSITIVE_INFINITY。

    import javafx.application.Application;
    import javafx.geometry.Insets;
    import javafx.geometry.Pos;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;
    
    import java.util.stream.Stream;
    
    public class Tester extends Application {
        private static final int WIDTH = 300;
        private static final int HEIGHT = 400;
    
        @Override
        public void start(Stage stage) {
            GridPane pane = new GridPane();
            pane.setGridLinesVisible(true);
            pane.setAlignment(Pos.TOP_LEFT);
            pane.setHgap(10);
            pane.setVgap(10);
            pane.setPadding(new Insets(10, 10, 10, 10));
    
            Button cat = new Button("cat");
            Button monkey = new Button("monkey");
            Button elephant = new Button("elephant and lion");
            pane.add(cat, 0, 0);
            pane.add(monkey, 0, 1);
            pane.add(elephant, 0, 2);
    
            Stream.of(cat, monkey, elephant).forEach(btn -> btn.setMaxWidth(Double.POSITIVE_INFINITY));
    
            Scene scene = new Scene(pane, WIDTH, HEIGHT);
            stage.setScene(scene);
            stage.show();
        }
    }
    
    推荐文章