我无法让我的 HBox 中的元素增长,所以我从 java2s.com 下载了以下示例代码.它作为一个最小的无效示例:
package fxtest;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Fxtest extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("");
Group root = new Group();
Scene scene = new Scene(root, 600, 250, Color.WHITE);
HBox hbox = new HBox();
TextField field = new TextField();
HBox.setHgrow(field, Priority.ALWAYS);
hbox.getChildren().addAll(new Label("Search:"), field, new Button("Go"));
root.getChildren().add(hbox);
primaryStage.setScene(scene);
primaryStage.show();
}
}
结果看起来like this .
如果我理解正确,TextField 应该增长,不是吗?
我的 Java 版本是 1.7.0_51
我的 JavaFX 版本是 2.2.51-b13
你知道为什么它不起作用/我必须做什么吗? 谢谢!
最佳答案
为什么 HBox.setHgrow对你不起作用
您使用 Group由于场景的根节点和组的大小不可调整,因此组的大小不会根据场景的大小进行调整。
A Group will take on the collective bounds of its children and is not directly resizable.
By default, a Group will "auto-size" its managed resizable children to their preferred sizes during the layout pass
一般来说,您很少希望将组用作场景的根节点。
如何修复
在场景中仅使用可调整大小的节点(Pane 子类或 Control 子类)。
示例
用下面的方法替换您的 start 方法,该方法删除 Group 根节点,而是使 HBox 成为场景的根节点:
public void start(Stage primaryStage) {
HBox hbox = new HBox(10);
TextField field = new TextField();
HBox.setHgrow(field, Priority.ALWAYS);
hbox.setAlignment(Pos.BASELINE_LEFT);
hbox.getChildren().addAll(
new Label("Search:"), field, new Button("Go")
);
hbox.setPadding(new Insets(10));
Scene scene = new Scene(hbox, 600, 250, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
}
调整窗口大小后的示例输出(您可以看到搜索文本字段根据请求扩大和缩小以适应可用空间):
关于JavaFX:setHgrow(...) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21865044/