-1

Please am developing a chess game using Java. I am having problems trying to display captured chess pieces, this pieces are held in a bufferedImage. when i run and print the variable of the bufferedImage it isn't null and doesn't display the image on the JPanel.

In addition my list of captured chess piece stored in a "List capturedPiece" and is working fine, also the paths to the images are correct. The only problem is that the image stored on the bufferedImage doesn't displaying.

Here is my code

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);


}

}

user3816650
  • 41
  • 1
  • 5

1 Answers1

3

Given these things you stated are true:

  • when i run and print the variable of the bufferedImage it isn't null
  • In addition my list of captured chess piece stored in a "List capturedPiece" and is working fine
  • also the paths to the images are correct.

A common problem will custom painting that the panel that the painting is being done on has not default preferred size (0x0). A panel only get increased preferred size based on more components being added to it. In the case of custom painting on a panel, you need to give the panel an explicit preferred size by overriding getPreferredSize()

@Override
public Dimension getPreferredSize() {
    return new Dimension(300, 300);
}

Without this, it can be hit or miss, whether or not you will see the contents of the panel. The determining factory is the layout manager of the parent container. Some layout managers will respect the preferred size (in which case, you won't see the contents) and some that won't respect preferred size (in which case, the panel will stretch to fit the container - where you may see the contents). Generally when custom painting, you always want to override the method. Have a look at this post to get an idea of which layout managers respect preferred sizes and which ones don't


If that doesn't work, I suggest you post an MCVE that we can run and test. Leave out all the unnecessary code that doesn't pertain to this problem. I'd sat just create a separate program that has nothing to do with your program, just a couple simple images being drawn to a panel, and add it to a frame. Something simple recreates the problem.


UPDATE

Don't use null layouts!

Use layout managers.. Your layout a null for the container you want to add the panel in question to, but you can't do that without setting the bounds. But forget that. Like I said, don't use null layouts. Learn to use the layout managers in the link. Let them do the position and sizing for you.
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • An (related) aside: I've seen this recommendatation about overriding `getPreferredSize` like this frequently. But it destroys the semantics of the method. I'd rather recommend to override it like here http://stackoverflow.com/a/23503703/3182664 ... but maybe this is not sooo important here. – Marco13 Jul 08 '14 at 14:23
  • @peeskillet, i have added the method getPreferredSize() and also chose a gridLayout but nothing happened – user3816650 Jul 08 '14 at 14:39
  • 2
    @user3816650 Then follow the second part of my answer. Post an MCVE. That we can compile and test – Paul Samsotha Jul 08 '14 at 14:44