在JavaFX中包装内容 [英] wrap content in JavaFX

查看:53
本文介绍了在JavaFX中包装内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
    }

}

这是输出:

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

Question: Can someone explain to me why the Vbox fill the whole screen? Is there a method that is similar to Android's wrap_content? I want the image below to be the output:

推荐答案

解决方案

将VBox包裹在 Group 中;例如使用:

Wrap the VBox in a Group; e.g. use:

container.getChildren().add(new Group(box));

代替:

container.getChildren().add(box);

为什么起作用

来自javadoc组:

From the Group javadoc:

默认情况下,组会在布局过程中将其可调整大小的可管理子级自动调整为"其首选大小.

By default, a Group will "auto-size" its managed resizable children to their preferred sizes during the layout pass.

这意味着VBox将不会超出其内容的首选大小(该大小恰好足以在其中显示标签).

This means that the VBox won't grow past the preferred size of it's content (which is just enough area to display the label inside it).

替代实现

将VBox的最大大小设置为首选大小.然后,VBox只会增长到足以容纳其中的内容的首选大小,并且永远不会增长到更大.

Set the maximum size of the VBox to the preferred size. Then the VBox will only ever grow large enough to fit the preferred size of the content inside it and will never grow any larger.

box.setMaxSize(VBox.USE_PREF_SIZE, VBox.USE_PREF_SIZE);

为什么默认情况下VBox会增长

这是一个可调整大小的容器会拉伸以填充可用区域.

It is a resizable container which will stretch to fill available area.

注意

我不知道该效果与我从未为Android开发的Android wrap_content方法完全相同,但是该效果似乎与您在问题中提供的第二张图片完全匹配.你想要的.

I don't know that the effect is exactly the same as an Android wrap_content method as I have never developed for Android, however the effect does seem to exactly match the second image you provided in your question, which appears to be what you want.

这篇关于在JavaFX中包装内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆