簡體   English   中英

在JavaFX中對對象進行分組?

[英]Grouping objects in JavaFX?

因此,我目前正在為Connect4游戲制作JavaFX GUI(使用SceneBuilder),我想知道是否存在一種將對象“分組”在一起以便可以對所有對象一起執行操作的方法?

我的意思示例:

  • 我有7個按鈕用於列(colButton1-7),我想立即禁用所有按鈕。
  • 我將Ellipses用於計數器(counter1-40),並希望將所有顏色更改為白色。

我四處搜尋,但找不到任何東西。 我知道如何對單個對象執行這兩項操作,但是無法想到一種輕松地將更改同時應用於所有更改的方法。 任何幫助,將不勝感激 :)

沒有分組機制可以對同一組的所有成員執行單個操作。 相反,您可以有一個組/容器來保存所有控件並將相同的操作應用於其每個成員。

例如,假設我有一個包含ButtonsVBox ,而我想全部禁用它們。

for(Node node:vBox.getChildren()) {
    node.setDisable(true);
}

或者,設置樣式

for(Node node:vBox.getChildren()) {
    node.setStyle("-fx-something");
}

對於禁用,如果禁用節點,則其所有子節點都將disabled設置為true。 因此,您可以執行以下操作:

VBox buttonHolder = new VBox();
Button button = new Button(...);
buttonHolder.getChildren().add(button);
// repeat as necessary...

buttonHolder.setDisable(true); // all buttons in the VBox will now be disbaled

對於樣式屬性,例如形狀的fill ,應使用外部樣式表。 如果更改父項的樣式類,則可以使用適當的外部樣式表一次更改所有子項的樣式。

例如

Pane counterPane = new Pane();
for (int i=0; i<numCounters; i++) {
    Ellipse counter = new Ellipse(...);
    counter.getStyleClass().add("counter");
    counterPane.getChildren().add(counter);
}

// ...

counterPane.getStyleClass().add("counter-pane"); // all counters white

// change to red:
counterPane.getStyleClass().remove("counter-pane");
counterPane.getStyleClass().add("warning");

外部樣式表:

.counter-pane > .counter {
    -fx-fill: white ;
}

.warning > .counter {
    -fx-fill : red ;
}

暫無
暫無

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

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