package example;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Text text = new Text("This is a Text");
VBox box = new VBox();
box.setAlignment(Pos.CENTER);
box.setStyle("-fx-background-color: yellow;");
box.getChildren().add(text);
StackPane container = new StackPane();
container.getChildren().add(box);
BorderPane bp = new BorderPane();
bp.setCenter(container);
Scene scene = new Scene(bp, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出:

问题:有人可以向我解释为什么 Vbox 会填满整个屏幕吗?有没有类似于Android的wrap_content的方法?我希望下面的图像是输出:

解决方案
将 VBox 包裹在一个组中;例如使用:
container.getChildren().add(new Group(box));
Run Code Online (Sandbox Code Playgroud)
代替:
container.getChildren().add(box);
Run Code Online (Sandbox Code Playgroud)
为什么有效
来自组 javadoc:
默认情况下,组将在布局过程中将其托管的可调整大小的子项“自动调整大小”为他们的首选大小。
这意味着 VBox 不会超过其内容的首选大小(该区域刚好足以显示其中的标签)。
替代实现
将 VBox 的最大大小设置为首选大小。然后 VBox 只会变得足够大以适应其中内容的首选大小,并且永远不会变得更大。
box.setMaxSize(VBox.USE_PREF_SIZE, VBox.USE_PREF_SIZE);
Run Code Online (Sandbox Code Playgroud)
为什么 VBox 默认增长
它是一个可调整大小的容器,可以拉伸以填充可用区域。
笔记
我不知道效果与我从未为 Android 开发的 Android wrap_content 方法完全相同,但是效果似乎与您在问题中提供的第二张图片完全匹配,这似乎是您想要的。
| 归档时间: |
|
| 查看次数: |
6903 次 |
| 最近记录: |