JavaFX代码重复

时间:2016-03-31 10:52:34

标签: java javafx duplicates code-duplication

我有22件物品(11件白色件和11件黑色件)。它们都有颜色和字母。我需要将带有图像的所有对象添加到javafx中的HBox。

我有以下代码可以使用:

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 个答案:

答案 0 :(得分: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");
        }
    }
}