Search code examples
javajpanelchess

How to save a specific part of a JPanel?


I am working on a chess game and I would like to let the player choose the board's colors. Therefore I will use this method:

    static void createBoard(Graphics g) {

    Color bright = new Color(255, 225, 181);    //player chooses color
    Color dark = new Color(188, 141, 105);      //player chooses color
    boolean darkTile = false;

    for (int y = spaceY; y < (spaceY + BOARDHEIGHT); y += TILESIZE) {
        for (int x = spaceX; x < (spaceX + BOARDWIDTH); x += TILESIZE) {
            if (darkTile) {
                g.setColor(dark);
            } else {
                g.setColor(bright);
            }
            g.fillRect(x, y, TILESIZE, TILESIZE);
            darkTile = !darkTile;
        }
        darkTile = !darkTile;
    }
    BufferedImage overlay;
    try {
        overlay = ImageIO.read(new File("overlay.png"));
        JLabel label = new JLabel(new ImageIcon(overlay));
        g.drawImage(overlay, spaceX, spaceY, BOARDWIDTH, BOARDHEIGHT, null);
    } catch (IOException e) {}
}

This I would like to save as a BufferedImage, so I don't have to run this method all the time.

So how can I save just this part of my JPanel, without the stuff outside of the chess board? (there will be more painted)


Solution

  • This I would like to save as a BufferedImage,

    Don't know that your need to save the BufferedImage to a file. You can just create a BufferedImage to be used by the application when the application starts. You can then recreate the BufferedImage if any of the user colors change.

    You can paint directly to a BufferedImage:

    BufferedImage image = new BufferedImage(boardSize, boardSize, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    
    // draw the squares onto board
    
    g2d.dispose();
    

    Now your createBoard() method should probably return the BufferedImage so it can be used by your application.