捕获的棋子的BufferedImage不会显示在我的JPanel上

时间:2014-07-08 13:52:59

标签: java swing chess

请使用Java开发国际象棋游戏。我在尝试显示捕获的棋子时遇到问题,这些棋子都保存在bufferedImage中。当我运行并打印bufferedImage的变量时,它不是null并且不会在JPanel上显示图像。

此外,我的捕获的棋子列表存储在“List capturePiece”中并且工作正常,图像的路径也是正确的。唯一的问题是存储在bufferedImage上的图像不显示。

这是我的代码

package chessgame.gui;

public class BrownPlayerPanel extends JPanel {

private Rectangle yellowPawnRect, yellowKnightRect, yellowBishopRect,
        yellowRookRect, yellowQueenRect;
private Rectangle brownPawnRect, brownKnightRect, brownBishopRect,
        brownRookRect, brownQueenRect;
private List<Piece> capturedPieces;
BufferedImage figurineLayer, counterLayer;
boolean firstPaint = true;
private ImageFactory fact;

BufferedImage piecetest;

public BrownPlayerPanel() {
    initComponents();
    fact = new ImageFactory();

}

public void setCapturedPieces(List<Piece> piece) {
    capturedPieces = piece;

    //System.out.println(capturedPieces);


    if (counterLayer != null) {
        clearBufferedImage(counterLayer);
    }

    if (figurineLayer != null) {
        clearBufferedImage(figurineLayer);
    }

    updateLayers();
    repaint();
}

private void initRects(int width, int height) {
    int gridWidth = width / 5;
    int gridHeight = height / 2;

    yellowPawnRect = new Rectangle(0, 0, gridWidth, gridHeight);
    yellowKnightRect = new Rectangle(gridWidth, 0, gridWidth, gridHeight);
    yellowBishopRect = new Rectangle(gridWidth * 2, 0, gridWidth, gridHeight);
    yellowRookRect = new Rectangle(gridWidth * 3, 0, gridWidth, gridHeight);
    yellowQueenRect = new Rectangle(gridWidth * 4, 0, gridWidth, gridHeight);

    brownPawnRect = new Rectangle(0, gridHeight, gridWidth, gridHeight);
    brownKnightRect = new Rectangle(gridWidth, gridHeight, gridWidth,gridHeight);
    brownBishopRect = new Rectangle(gridWidth * 2, gridHeight, gridWidth,gridHeight);
    brownRookRect = new Rectangle(gridWidth * 3, gridHeight, gridWidth,gridHeight);
    brownQueenRect = new Rectangle(gridWidth * 4, gridHeight, gridWidth,gridHeight);

}

public void clearBufferedImage(BufferedImage image) {
    Graphics2D g2d = image.createGraphics();
    g2d.setComposite(AlphaComposite.Src);
    g2d.setColor(new Color(0, 0, 0, 0));
    g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
    g2d.dispose();
}

private void updateLayers() {
    int yPC = 0, yNC = 0, yBC = 0, yRC = 0, yQC = 0;
    int bPC = 0, bNC = 0, bBC = 0, bRC = 0, bQC = 0;

    if (firstPaint) {
        int width = this.getWidth();
        int height = this.getHeight();

        figurineLayer = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        counterLayer = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);

        capturedPieces = new ArrayList<Piece>();

        initRects(width, height);

        firstPaint = false;
    }

    int width = this.getWidth();
    int height = this.getHeight();
    int gridWidth = width / 5;

    for (Piece piece : capturedPieces) {
        if (piece.getColor() == Piece.YELLOW_COLOR) {
            if (piece.getType() == Piece.TYPE_PAWN) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR, Piece.TYPE_PAWN),yellowPawnRect);
                yPC++;
            }

            if (piece.getType() == Piece.TYPE_KNIGHT) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_KNIGHT),yellowKnightRect);
                yNC++;
            }

            if (piece.getType() == Piece.TYPE_BISHOP) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_BISHOP),yellowBishopRect);
                yBC++;
            }

            if (piece.getType() == Piece.TYPE_ROOK) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR, Piece.TYPE_ROOK), yellowRookRect);
                yRC++;
            }

            if (piece.getType() == Piece.TYPE_QUEEN) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.YELLOW_COLOR,Piece.TYPE_QUEEN), yellowQueenRect);
                yQC++;
            }
        }



        if (piece.getColor() == Piece.BROWN_COLOR) {
            if (piece.getType() == Piece.TYPE_PAWN) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_PAWN),brownPawnRect);
                System.out.println(getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_PAWN).getWidth());
                bPC++;
            }

            if (piece.getType() == Piece.TYPE_KNIGHT) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_KNIGHT),brownKnightRect);
                bNC++;
            }

            if (piece.getType() == Piece.TYPE_BISHOP) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_BISHOP),brownBishopRect);
                bBC++;
            }

            if (piece.getType() == Piece.TYPE_ROOK) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR, Piece.TYPE_ROOK),brownRookRect);
                bRC++;
            }

            if (piece.getType() == Piece.TYPE_QUEEN) {
                drawImageIntoLayer(figurineLayer, getFigurineImage(Piece.BROWN_COLOR,Piece.TYPE_QUEEN), brownQueenRect);
                bQC++;
            }
        }
    }

    if (yPC > 1) {
        drawCounterIntoLayer(counterLayer, yPC, yellowPawnRect);
    }
    if (yNC > 1) {
        drawCounterIntoLayer(counterLayer, yNC, yellowKnightRect);
    }
    if (yBC > 1) {
        drawCounterIntoLayer(counterLayer, yBC, yellowBishopRect);
    }
    if (yRC > 1) {
        drawCounterIntoLayer(counterLayer, yRC, yellowRookRect);
    }
    if (yQC > 1) {
        drawCounterIntoLayer(counterLayer, yQC, yellowQueenRect);
    }

    if (bPC > 1) {
        drawCounterIntoLayer(counterLayer, bPC, brownPawnRect);
    }
    if (bNC > 1) {
        drawCounterIntoLayer(counterLayer, bNC, brownKnightRect);
    }
    if (bBC > 1) {
        drawCounterIntoLayer(counterLayer, bBC, brownBishopRect);
    }
    if (bRC > 1) {
        drawCounterIntoLayer(counterLayer, bRC, brownRookRect);
    }
    if (bQC > 1) {
        drawCounterIntoLayer(counterLayer, bQC, brownQueenRect);
    }
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(figurineLayer, 10,10, this);
    g2d.drawImage(counterLayer, null, this);

}

private void drawCounterIntoLayer(BufferedImage canvas, int count,Rectangle whereToDraw) {
    Graphics2D g2d = canvas.createGraphics();
    g2d.setFont(new Font("Arial", Font.BOLD, 12));
    g2d.setColor(Color.black);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    FontMetrics textMetrics = g2d.getFontMetrics();
    String countString = Integer.toString(count);
    int xCoord = whereToDraw.x + whereToDraw.width - textMetrics.stringWidth(countString);
    int yCoord = whereToDraw.y + whereToDraw.height;
    g2d.drawString(countString, xCoord, yCoord);
    g2d.dispose();
}

private void drawImageIntoLayer(BufferedImage canvas, BufferedImage item,Rectangle r) {
    Graphics2D g2d = canvas.createGraphics();
    g2d.drawImage(item, r.x, r.y, r.width, r.height, this);
    g2d.dispose();

}

private void initComponents() {
    setName("Form");
    setBounds(0, 0, 250, 146);
    setBorder(new LineBorder(new Color(139, 69, 19)));
    GroupLayout groupLayout = new GroupLayout(this);
    groupLayout.setHorizontalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGap(0, 698, Short.MAX_VALUE)
    );
    groupLayout.setVerticalGroup(
        groupLayout.createParallelGroup(Alignment.LEADING)
            .addGap(0, 448, Short.MAX_VALUE)
    );
    setLayout(groupLayout);

    setBackground(Color.black);

}

private BufferedImage getFigurineImage(int color, int type) {

    BufferedImage ImageToDraw = null;
    try {
        String filename = "";

        filename += (color == Piece.YELLOW_COLOR ? "Yellow" : "Brown");
        switch (type) {
        case Piece.TYPE_BISHOP:
            filename += "b";
            break;
        case Piece.TYPE_KING:
            filename += "k";
            break;
        case Piece.TYPE_KNIGHT:
            filename += "n";
            break;
        case Piece.TYPE_PAWN:
            filename += "p";
            break;
        case Piece.TYPE_QUEEN:
            filename += "q";
            break;
        case Piece.TYPE_ROOK:
            filename += "r";
            break;
        }
        filename += ".png";

        URL urlPiece = getClass().getResource("/chessgame/res/" + filename);
        ImageToDraw = ImageIO.read(urlPiece);

    } catch (IOException io) {
    }

    return ImageToDraw;

}   

}

ChessWindow Class:

public class ChessWindow extends JFrame {

private static final long serialVersionUID = 1L;
private JPanel contentPane;
private BoardGUI boardgui;
private Game game;
JPanel panel_1;
public JLabel lblNewLabel;
private XmlRpcServer server;
private static final int PLAYER_OPTION_SWING = 1;
private static final int PLAYER_OPTION_AI = 2;
private static final int PLAYER_OPTION_NETWORK = 3;

String gameIdOnServer, gamePassword;


public ChessWindow(int yellowPlayerOption, int brownPlayerOption,Game game, String    gameIdOnServer, String gamePassword) {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 776, 583);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("File");
    menuBar.add(mnFile);

    JMenuItem mntmNewGame = new JMenuItem("New Game");
    mnFile.add(mntmNewGame);

    JSeparator separator = new JSeparator();
    mnFile.add(separator);

    JSeparator separator_1 = new JSeparator();
    mnFile.add(separator_1);

    JSeparator separator_2 = new JSeparator();
    mnFile.add(separator_2);

    JMenuItem mntmAccount = new JMenuItem("Account");
    mnFile.add(mntmAccount);

    JSeparator separator_10 = new JSeparator();
    mnFile.add(separator_10);

    JMenuItem mntmExit = new JMenuItem("Exit");
    mnFile.add(mntmExit);

    JMenu mnTactics = new JMenu("Tactics");
    menuBar.add(mnTactics);

    JMenuItem mntmTactics = new JMenuItem("Tactics 1");
    mnTactics.add(mntmTactics);

    JMenuItem mntmTactics_1 = new JMenuItem("Tactics 2");
    mnTactics.add(mntmTactics_1);

    JMenu mnServer = new JMenu("Server");
    menuBar.add(mnServer);

    JMenuItem mntmServerStatus = new JMenuItem("Server Status");
    mntmServerStatus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //String gameId = "Game ID:" + server.getGameIdOnServer();
            JOptionPane.showMessageDialog(boardgui,
                    server.gameIdOnServer,
                    "A plain message",
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    mnServer.add(mntmServerStatus);

    JMenuItem mntmServerLog = new JMenuItem("Server Log");
    mntmServerLog.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JavaConsole console = new JavaConsole();
            console.frame.setVisible(true);
            console.frame.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        }
    });
    mnServer.add(mntmServerLog);

    JMenuItem mntmViewOnlinePlayers = new JMenuItem("View Online Players");
    mnServer.add(mntmViewOnlinePlayers);

    JMenu mnStatistics = new JMenu("Statistics");
    menuBar.add(mnStatistics);

    JMenuItem mntmHumanStatsAgainst = new JMenuItem("Human Stats Against Computer");
    mnStatistics.add(mntmHumanStatsAgainst);

    JSeparator separator_8 = new JSeparator();
    mnStatistics.add(separator_8);

    JMenuItem mntmComputerStatsAgainst = new JMenuItem("Computer Stats Against Itself");
    mnStatistics.add(mntmComputerStatsAgainst);

    JSeparator separator_9 = new JSeparator();
    mnStatistics.add(separator_9);

    JMenuItem mntmHumanStatsAgains = new JMenuItem("Human Stats Agains Human");
    mnStatistics.add(mntmHumanStatsAgains);

    JMenuItem mntmAlgorithmInformation = new JMenuItem("Algorithm Information");
    mnStatistics.add(mntmAlgorithmInformation);

    JMenu mnOptions = new JMenu("Options");
    menuBar.add(mnOptions);

    JMenu mnTest = new JMenu("Test");
    mnOptions.add(mnTest);

    JMenuItem mntmPiecePosition = new JMenuItem("Piece Position");
    mnTest.add(mntmPiecePosition);

    JMenuItem mntmPieceMoves = new JMenuItem("Piece Moves");
    mnTest.add(mntmPieceMoves);

    JSeparator separator_11 = new JSeparator();
    mnOptions.add(separator_11);

    JMenuItem mntmConsole = new JMenuItem("Console");
    mntmConsole.addActionListener(new ConsoleController());
    mnOptions.add(mntmConsole);

    JMenu mnHelp = new JMenu("Help");
    menuBar.add(mnHelp);

    JMenuItem mntmRulesOfChess = new JMenuItem("Rules of Chess");
    mnHelp.add(mntmRulesOfChess);

    JMenuItem mntmAbout = new JMenuItem("About");
    mnHelp.add(mntmAbout);


    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout(0, 0));

    JPanel panel = new JPanel();
    contentPane.add(panel, BorderLayout.NORTH);
    panel.setBounds(0, 0, 50, 50);

    lblNewLabel = new JLabel("text");
    panel.add(lblNewLabel);

    JSplitPane splitPane = new JSplitPane();
    splitPane.setResizeWeight(0.1);
    contentPane.add(splitPane, BorderLayout.CENTER);

    game = new Game();
    boardgui = new BoardGUI(game);
    splitPane.setLeftComponent(boardgui);
    GameConfig(yellowPlayerOption, brownPlayerOption, game, gameIdOnServer,  gamePassword,  boardgui);  

    StatusPanel panel_1 = new StatusPanel();
    contentPane.add(panel_1, BorderLayout.SOUTH);

    boardgui.lblGameState = new JLabel();
    panel_1.add(boardgui.lblGameState);

    JPanel panel_2 = new JPanel();
    splitPane.setRightComponent(panel_2);
    panel_2.setBounds(0, 0, 50, 300);
    panel_2.setLayout(null);

    BrownPlayerPanel brown = new BrownPlayerPanel();
    panel_2.add(brown);

    MovesHistoryPanel moveDisplay = new MovesHistoryPanel();
    moveDisplay.setBorder(new LineBorder(new Color(139, 69, 19)));
    panel_2.add(moveDisplay);

    YellowPlayerPanel yellow = new YellowPlayerPanel();
    yellow.setBorder(new LineBorder(new Color(139, 69, 19)));
    panel_2.add(yellow);


}

}

1 个答案:

答案 0 :(得分:3)

鉴于这些事情你说的是真的:

  • 当我运行并打印bufferedImage的变量时,它不是
  • 此外,我的捕获的棋子列表存储在&#34; List capturedPiece&#34;并且工作正常
  • 图片的路径也是正确的。

一个常见的问题是自定义绘制正在进行绘制的面板没有默认的首选大小(0x0)。面板仅根据添加到其中的更多组件而获得增加的首选大小。如果在面板上进行自定义绘制,则需要通过覆盖getPreferredSize()

为面板指定明确的首选大小
@Override
public Dimension getPreferredSize() {
    return new Dimension(300, 300);
}

如果没有这个,它可能会被击中或错过,无论你是否会看到面板的内容。确定工厂是父容器的布局管理器。一些布局管理员会尊重首选尺寸(在这种情况下,您不会看到内容)和一些不会尊重首选尺寸(在这种情况下,面板将拉伸以适应容器 - 您在哪里可以看到内容)。通常在自定义绘制时,您总是希望覆盖该方法。请查看this post,了解哪些布局管理员尊重首选尺寸,哪些布局管理员不会


如果这不起作用,我建议你发布一个我们可以运行和测试的MCVE。省去与此问题无关的所有不必要的代码。我只是创建了一个单独的程序,其中 nothing 与您的程序无关,只需将几个简单的图像绘制到面板上,然后将其添加到框架中。简单的东西重现了这个问题。


<强>更新

不要使用空布局!

Use layout managers.。对于要添加相关面板的容器,您的布局为null,但是如果不设置边界,则无法执行此操作。但忘了。就像我说的,不要使用null布局。学习使用链接中的布局管理器。让他们为你做位置和尺寸。