在这种情况下,您需要将按钮的最大宽度设置为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();
}
}