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

Pav*_*l_K 3 java javafx

我有一个HBox和两个(或更多)Button.我希望所有的按钮宽度相同.我无法设置按钮的宽度(以像素为单位),因为文本是从每种语言的资源包中获取的(因此文本的长度是可变的).这是我尝试的代码,但没有成功:

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();
Run Code Online (Sandbox Code Playgroud)

我的错是什么?

Ita*_*iha 6

您需要maxWidth将Button 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


MBe*_*Bec 4

将按钮最大宽度设置为最大值:

but1.setMaxWidth(Double.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)

但它只会调整按钮大小以填充水平盒宽度。如果需要相同宽度的按钮,则应找到最长的按钮,然后将其宽度设置为其他按钮。

but1.setPrefWidth(width);
Run Code Online (Sandbox Code Playgroud)