简体   繁体   English

JavaFX:HBox中具有相同宽度的按钮

[英]JavaFX: Button(s) in HBox with same width

I have a HBox and two (or more) Button's in it. 我有一个HBox和两个(或更多)Button。 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. 您需要将Button的maxWidth设置为Double.MAX_VALUE ,并将HBox.setHgrow()设置为Priority.ALWAYS以使Button填充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. 但它只会调整按钮大小以填充hbox宽度。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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