簡體   English   中英

用於FXML布局的可重用常量?

[英]Reusable constants for FXML layouts?

這是我先前問題的跟進。 不知何故,我從這里得到了問題的解決方案,但是由於某些原因,它從未真正回答我的問題,這導致我提出了這個問題。

原因如下:

  • 我發現通過使用FXMLLoader.namespace ,映射的值僅可用於正在加載FXMLLoader的布局(FXML文件)。 但是,這並不能滿足其他FXML文件具有可重用常量的需求。
  • 另外,由於這些常量是在Java代碼中定義的,因此使用它們時,IDE會將其視為錯誤,因為它們沒有直接在FXML文件中定義,因此很難追蹤其他異常錯誤。

所以現在的問題是,如何使常量可重用於FXML布局?

與Android中一樣,例如Color資源

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="white">#FFFFFF</color>
</resources>

可以應用於XML布局的屬性:

android:textColor="@color/white"

JavaFX中還有其他可能的方法嗎? 感謝所有答案。

最接近的是通過樣式表的CSS。

Constants.css

* {
    -my-color: #FFFFFF;
    -my-width: 300;
    -my-height: 400;
}

然后,您可以通過CSS在任何地方使用它。 壞消息是您必須在應用此功能的所有位置添加Constants.css

在代碼中:

pane.setStyle("-fx-background-color: -my-color;");

在FXML中:

<Pane style="-fx-background-color: -my-color;" .... />

在另一個特定的CSS文件中:

.my-pane {
    -fx-background-color: -my-color;
}

因此,我想出了一個解決方案,並想回答自己的問題。 這不是最好的,但我希望將來會有用。

這非常簡單,我們可以為每個常量字段定義一個getter方法,在這種情況下,我們可以使用Expression Binding從FXML輕松訪問它們的值。 這是一個例子:

Theme.class

package styles;

import javafx.scene.paint.Color;

public final class Theme {

  /** Constant field; use Theme.BASE_COLOR */
  public static final Color BASE_COLOR = Color.TEAL;

  /** Getter method for FXML; use ${theme.baseColor} */
  public Color getBaseColor() { return BASE_COLOR; }
}

layout.fxml

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

<?import javafx.scene.layout.HBox?>
<?import javafx.scene.text.Text?>

<HBox xmlns="http://javafx.com/javafx"
      xmlns:fx="http://javafx.com/fxml"
      alignment="CENTER">

  <fx:define>
    <!--
        Define a reference to our Theme class.
        This is convenient because we only need a single
        instance of our Theme class for every FXML file.
    -->
    <styles.Theme fx:id="theme"/>
  </fx:define>

  <children>
    <!-- Now, we can simply use an expression binding here -->
    <Text text="Hello, World!" fill="${theme.baseColor}"/>
  </children>

</HBox>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM