JavaFX:如何给多个相同大小的圆圈?

JavaFX: How to give more than one Circle the same size?

我的问题看起来很简单,但是我还没有找到好的方法。我想在我的 FXML 中定义几个圆,10 个圆的半径应为 10px,另外 20 个圆的半径应为 6px。我想一次性声明尺寸,这样我就可以轻松更改它。

我没发现 if/how 可以在 FXML 中声明变量,这是最简单的方法。所以我希望 CSS 能帮助我,这会更好:我试图给圆圈两个 styleClasses 并为 CSS 中的圆圈设置大小,但似乎没有 属性 缩放圆。

<Circle fx:id="c00" centerX="100" centerY="100" styleClass="circle10" /> 

另一个想法是覆盖 Circle class 并将半径设置为所需的值。但我不认为这是一个干净的代码,因为布局应该在 FXML 和 CSS 中进行,而不是在 Java 中进行。

必须有一种方法可以做到这一点而不会弄乱那个地方的 Java 代码。

在此先感谢您的帮助! 米斯米尔

在 FXML 中,如果您想定义一个可以在多个地方使用的变量,请使用 fx:define。来自 Introduction to FXML:

The <fx:define> element is used to create objects that exist outside of the object hierarchy but may need to be referred to elsewhere.

For example, when working with radio buttons, it is common to define a ToggleGroup that will manage the buttons' selection state. This group is not part of the scene graph itself, so should not be added to the buttons' parent. A define block can be used to create the button group without interfering with the overall structure of the document:

<VBox>
    <fx:define>
        <ToggleGroup fx:id="myToggleGroup"/>
    </fx:define>
    <children>
        <RadioButton text="A" toggleGroup="$myToggleGroup"/>
        <RadioButton text="B" toggleGroup="$myToggleGroup"/>
        <RadioButton text="C" toggleGroup="$myToggleGroup"/>
    </children> 
</VBox>

Elements in define blocks are usually assigned an ID that can be used to refer to the element's value later. IDs are discussed in more detail in later sections.

下面是定义半径的示例 Circle:

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

<?import java.lang.Double?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.shape.Circle?>

<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" spacing="10.0" alignment="CENTER">

    <padding>
        <Insets topRightBottomLeft="10.0"/>
    </padding>

    <fx:define>
        <Double fx:id="smallRadius" fx:value="50.0"/>
        <Double fx:id="largeRadius" fx:value="100.0"/>
    </fx:define>

    <Circle radius="$smallRadius"/>
    <Circle radius="$largeRadius"/>
    <Circle radius="$smallRadius"/>
    <Circle radius="$largeRadius"/>

</VBox>