【问题标题】:set VBox width to width of smaller of children in javafx将 VBox 宽度设置为 javafx 中较小子项的宽度
【发布时间】:2018-04-21 14:59:41
【问题描述】:

我想弄清楚如何让 VBox 使首选宽度成为孩子宽度中的较小者?实际上,我希望第二个孩子成为设置宽度的决定因素,然后第一个孩子的大小将适合 VBox,因为它可以将文本包裹在里面。

例如,我有一个包含两个 HBox 子级的 VBox,每个子级内部都有一个标签。

所有子级的 VBox 大小

但我想要的是让 VBox 由较小的孩子自己调整大小:

VBox 尺寸适合较小的孩子

VBox 将为对话框设置场景,而我的例程将通过一个函数由其他人提供第二个框,我希望第二个框设置框的宽度而不是第一个,因为第一个可能会很长。

我不想使用固定数字来设置宽度,这就是我遇到这个问题的原因。

我可以只使用 XML 中的参数来做到这一点,还是必须使用一些 Java 代码调用来将事物绑定在一起?

我一直在 SceneBuilder 中玩这个,但没有成功。 fxml 如下所示:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>


<VBox minHeight="-Infinity" minWidth="0.0" spacing="2.0" style="-fx-border-color: yellow;" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <HBox id="box1" style="-fx-border-color: blue;">
         <children>
            <Label text="Text label one is really long" wrapText="true" />
         </children>
      </HBox>
      <HBox id="box2" style="-fx-border-color: red;">
         <children>
            <Label text="Text label two" />
         </children>
      </HBox>
   </children>
   <padding>
      <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
   </padding>
</VBox>

【问题讨论】:

    标签: javafx vbox


    【解决方案1】:

    box1 的首选宽度绑定到box2 的实际宽度。您可以在 FXML 中执行此操作(但可能不在 Scene Builder 中),但请注意,您需要提供 box2fx:id(而不是 id)才能使其工作:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.geometry.Insets?>
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.layout.HBox?>
    <?import javafx.scene.layout.VBox?>
    
    
    <VBox minHeight="-Infinity" minWidth="0.0" spacing="2.0" style="-fx-border-color: yellow;" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1">
       <children>
          <HBox id="box1" style="-fx-border-color: blue;" prefWidth="${box2.width}" >
             <children>
                <Label text="Text label one is really long" wrapText="true" />
             </children>
          </HBox>
          <HBox fx:id="box2" style="-fx-border-color: red;">
             <children>
                <Label text="Text label two" />
             </children>
          </HBox>
       </children>
       <padding>
          <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
       </padding>
    </VBox>
    

    【讨论】:

    • 谢谢 James_D,这是一个完美的解决方案!
    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多