0
我有22件物件(11個白色碎片和11個黑色碎片)。他們都有一個顏色和一個字母。我需要將所有這些具有圖像的對象添加到javafx中的HBox中。JavaFX代碼複製
我有下面的代碼工作:
public void draw(){
Paint border;
Paint fill;
for (Piece piecesObjects : pieces){
Group group = new Group();
Hexagon hexagon = new Hexagon();
if (piecesObjects.isWhite()){
border = Color.WHITE;
fill = Color.BLACK;
ImageView imageView = new ImageView("/hive/imagesPieces/b/" + piecesObjects.getPiece() + ".png");
group.getChildren().addAll(hexagon,imageView);
whitePieces.getChildren().add(group);
} else {
border = Color.BLACK;
fill = Color.WHITE;
ImageView imageView = new ImageView("/hive/imagesPieces/w/" + piecesObjects.getPiece() + ".png");
group.getChildren().addAll(hexagon,imageView);
blackPieces.getChildren().add(group);
}
hexagon.setStroke(border);
hexagon.setFill(fill);
}
}
正如你可以看到有很多重複的,我想知道如何解決這個問題。我試圖做到以下幾點:
public void draw(HBox hbox){
Paint border;
Paint fill;
for (Piece piecesObjects : pieces){
Group group = new Group();
Hexagon hexagon = new Hexagon();
if (piecesObjects.isWhite()){
border = Color.WHITE;
fill = Color.BLACK;
} else {
border = Color.BLACK;
fill = Color.WHITE;
}
hexagon.setStroke(border);
hexagon.setFill(fill);
ImageView imageView = new ImageView("/hive/imagesPieces/" + pieceObject.getColor() + "/" + piecesObjects.getPiece() + ".png");
group.getChildren().addAll(hexagon,imageView);
hBox.getChildren().add(group);
}
}
public void drawWhitepieces(){
draw(whitePieces);
}
public void drawBlackpieces(){
draw(blackPieces);
}
但是這段代碼仍然在每個HBox中繪製了22個不應該被允許的東西。 (正常,因爲它畫22個六邊形)。