我有两个
Button
和两个ComboBox
。按钮的宽度未知,因为文本取决于语言。按钮最宽的 ComboBox
必须拉伸到最大,其他 ComboBox
必须具有相同的宽度(我的意思是 comboBox1.getWidth()
必须等于 comboBox2.getWidth()
)。
这是我的代码:
public class JavaFxTest7 extends Application {
@Override
public void start(Stage stage) {
var button1 = new Button("Text with unknown length");
var comboBox1 = new ComboBox<String>();
comboBox1.setEditable(true);
comboBox1.setMaxWidth(Double.MAX_VALUE);
var toolBar1 = new ToolBar(comboBox1, button1);
HBox.setHgrow(comboBox1, Priority.ALWAYS);
var button2 = new Button("Another text with unknown length");
var comboBox2 = new ComboBox<String>();
comboBox2.setEditable(true);
comboBox2.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(comboBox2, Priority.ALWAYS);
var toolBar2 = new ToolBar(comboBox2, button2);
Scene scene = new Scene(new VBox(toolBar1, toolBar2), 800, 200);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
谁能告诉我怎么做吗?
问题是不知道什么comboBox会更宽。
但是您可以通过生成布局通道(将 CSS 和布局应用到场景或节点树)来解决这个问题。之后,场景中所有事物的默认宽度都会被计算出来并可以被调用。
因此,如果按钮的宽度是组合框长度计算应基于的度量,那么您可以运行布局过程,找出按钮的实际宽度是多少,并绑定最大宽度组合框到适当(最短宽度)组合框的实际宽度。
scene.getRoot().applyCss();
scene.getRoot().layout();
if (button1.getWidth() < button2.getWidth()) {
comboBox1.maxWidthProperty().bind(comboBox2.widthProperty());
} else {
comboBox2.maxWidthProperty().bind(comboBox1.widthProperty());
}