简体   繁体   中英

JavaFX: Button(s) in HBox with same width

I have a HBox and two (or more) Button's in it. And I want all the buttons be of the same width. I can't set width of the buttons in pixels because texts are taken from resource bundle for every language (so length of the text is variable). This is the code I tried, but didn't succeed:

Button but1=new Button("Long text");
Button but2=new Button ("Text");
HBox.setHgrow(but1, Priority.ALWAYS);
HBox.setHgrow(but2, Priority.ALWAYS);
HBox hbox=new HBox();
hbox.getChildren().addAll(but1,but2);
Scene scene=new Scene(hbox, 1000, 600);
stage.setScene(scene);
stage.show();

What is my mistake?

You need to set the maxWidth of the Button to Double.MAX_VALUE and also set HBox.setHgrow() to Priority.ALWAYS to make the Button fill the available width in the HBox.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Button but1 = new Button("Long text");
        Button but2 = new Button ("Text");
        HBox hbox=new HBox();
        hbox.getChildren().addAll(but1,but2);

        but1.setMaxWidth(Double.MAX_VALUE);
        but2.setMaxWidth(Double.MAX_VALUE);
        HBox.setHgrow(but1, Priority.ALWAYS);
        HBox.setHgrow(but2, Priority.ALWAYS);

        Scene scene=new Scene(hbox, 1000, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Set button maximum width to maximum value:

but1.setMaxWidth(Double.MAX_VALUE);

But it will only resize buttons to fill hbox width. If you need buttons with the same width, you should find the longest button and then set its width to other buttons.

but1.setPrefWidth(width);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM