不等大小的按钮JavaFX

时间:2017-05-17 05:36:02

标签: button javafx

当我使用以下代码在gridpane中创建2个按钮时,它为我提供了2个不等大小的按钮。我该如何解决这个问题?

/**
 * Set the appearance of buttons in the grid
 */
private void setButtonAppearance(Button button)
{
    button.setAlignment(Pos.CENTER);
    //button.setFont(font);
    button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
    button.setMinSize(Double.MIN_VALUE, Double.MIN_VALUE);
    // doesn't start with focus or stay focused
    button.setFocusTraversable(false);
}

/**
 * Create buttons to perform allocation and deallocation of events to venues
 */
private void addButtons()
{
    allocateButton = new Button("Allocate Event");
    deallocateButton = new Button("Deallocate Event");

    //Set appearance of buttons
    setButtonAppearance(allocateButton);
    setButtonAppearance(deallocateButton);

    gridPane.add(allocateButton, 5, 30, 10, 1);
    gridPane.add(deallocateButton, columns-15, 30, 10, 1);
}

输出: enter image description here

问候!

1 个答案:

答案 0 :(得分:1)

有两种可能的解决方案,要么为按钮设置首选宽度

private void setButtonAppearance(Button button) {
    button.setPrefWidth(60);
}

或设置按钮出现的列都具有相同的约束。像这样的东西。注意,默认情况下,getColumnConstraints()数组中没有任何ColumnConstraint对象。

gridPane.getColumnConstraints()
        .add(new ColumnConstraints(10, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));
gridPane.getColumnConstraints()
        .add(new ColumnConstraints(10, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));

自包含示例

@Override
public void start(Stage primaryStage) throws Exception {
    Button allocateButton = new Button("Allocate Event");
    Button deallocateButton = new Button("Deallocate Event");

    setButtonAppearance(allocateButton);
    setButtonAppearance(deallocateButton);

    GridPane gridPane = new GridPane();
    gridPane.add(allocateButton, 0, 0, 1, 1);
    gridPane.add(deallocateButton, 2, 0, 1, 1);
    gridPane.getColumnConstraints()
            .add(new ColumnConstraints(10, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));
    gridPane.getColumnConstraints()
            .add(new ColumnConstraints(10, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));
    gridPane.getColumnConstraints()
            .add(new ColumnConstraints(10, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));

    primaryStage.setScene(new Scene(gridPane));
    primaryStage.show();
}

private void setButtonAppearance(Button button) {
    button.setAlignment(Pos.CENTER);
    // button.setFont(font);
    button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
    button.setMinSize(Double.MIN_VALUE, Double.MIN_VALUE);
    // doesn't start with focus or stay focused
    button.setFocusTraversable(false);
}

无论哪种方式,我建议不要手工编写JavaFX布局,而是利用Scene Builder和FXML ...