2016-03-31 83 views
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個六邊形)。

回答

1

爲單件創建輔助方法,而不是多件。現在,您的版本的方法遍歷片段列表並添加它們,而不考慮顏色,這顯然不是您想要的。

private draw(Pane parent, Piece piece, Color stroke, String dir) { 
    Hexagon hexagon = new Hexagon(); 
    hexagon.setStroke(stroke); 
    hexagon.setFill(stroke.invert()); 

    ImageView imageView = new ImageView("/hive/imagesPieces/" + dir + "/" + piece.getPiece() + ".png"); 
    Group group = new Group(hexagon, imageView); 
    parent.getChildren().add(group); 
} 

public void draw() { 
    for (Piece piece : pieces) { 
     if (piece.isWhite()){ 
      draw(whitePieces, piece, Color.WHITE, "b"); 
     } else { 
      draw(blackPieces, piece, Color.BLACK, "w"); 
     } 
    } 
}