如何在一行中设置FXML“填充”属性

时间:2019-08-20 11:14:08

标签: java javafx padding coercion type-coercion

我想以与C#XAML文件相同的方式定义按钮的填充。而不是像这样写东西:

let encryptedText = _self._AESEncryptDecryptService.encrypt("Hello World");
let decryptedText = _self._AESEncryptDecryptService.decrypt(encryptedText);

,这样写起来会更容易:

<Button fx:id="btn1" ...>
    <padding>
        <Insets top="0" right="5" bottom="10" left="5" />
    </padding>
</Button>

<Button fx:id="btn2" ...>
    <padding>
        <Insets topRightBottomLeft="5" />
    </padding>
</Button>

我不知道为什么对“ padding”属性有此限制。我在FXML documentation上看到,可以为给定类型实现 valueOf() 方法来实现类型强制

<Button fx:id="btn1" ... padding="0 5 10 5" />
<Button fx:id="btn2" ... padding="5" />

但是我不知道将其放置在哪里,因为 Insets 类已被锁定(JDK)。因为这是一个静态方法,所以我认为该方法可以在其他地方实现,但是启动应用程序总是会给我带来强制错误:

public static Insets valueOf(String info) {
    // Data retrieval
}

目前,我发现的唯一解决方案是:

  • 定义一个名为 GButton 的新FXML组件,该组件继承了 Button
  • 定义一个继承了 Insets Spacing 类,并为此类实现 valueOf 方法
  • 为GButton添加一个“ space”属性(实例为 ObjectProperty ),该属性具有与“ padding”相同的行为,并定义其getter和setter。

是否有一种简单的方法可以将FXML“ padding”定义到Button标记中,而无需创建从Insets继承的类?
如果问题有用,请别忘了投票:)

2 个答案:

答案 0 :(得分:2)

  

我不知道为什么对“ padding”属性有此限制。我已经在FXML文档中看到,可以为给定类型实现valueOf()方法来强制类型强制

这将需要Insets来实现static valueOf(String)方法。该方法在该类型中不存在。因此,您不能简单地通过属性指定值。

Introduction to FXML

  

可以通过在目标类型上定义一种static valueOf()方法 来实现其他转换。

您可以使用style属性通过CSS来指定值。这通常比将对象分配给属性要短:

<Button fx:id="btn1" style="-fx-padding: 0 5 10 5;" .../>

有关受支持的属性/语法的更多信息,请查看the CSS Reference Guide

答案 1 :(得分:0)

我知道这个问题很老,但希望我能提供一些有见地的信息。我有同样的问题;不幸的是,FXML 没有完整的文档,但在我看来,将初始化模型拼凑在一起使其变得直观。

无论如何,你的方法是正确的,只是没有完全完成:

int16_t x=33;
void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);

}

void loop() {
  // put your main code here, to run repeatedly:

Serial.println(x);
delay(100);

x=x+1;
if(x==97)
{
x=32;
}

}

将创建一个与 CSS 的 <padding> <Insets top="10" right="20" bottom="30" left="40"/> </padding> 等效的填充,当然,您可以更改(甚至可以使用我假设的 FXML 变量)。

但是,一般而言,任何在适当约定中具有 padding: 10 20 30 40 属性的类(请参阅 this tutorial 以获得解释),您都可以很容易地在 FXML 中创建自定义组件并分配成员值,就像您可以使用上面的 javafx.beans

希望对大家有所帮助!