如何保存 JPanel 的特定部分?

How to save a specific part of a JPanel?

我正在开发一款国际象棋游戏,我想让玩家选择棋盘的颜色。因此我会使用这个方法:

    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) {}
}

我想将其保存为 BufferedImage,因此我不必一直运行此方法。

那么我怎样才能只保存我的 JPanel 的这一部分,而没有棋盘之外的东西呢? (会多画)

您为提出问题付出了一定的努力,所以让我们以一些想法来纪念您。

首先:您有一个空的 catch 块 {}。那是不好的做法。这只会吃掉您收到的任何错误消息。那是没有帮助的。要么允许该异常冒泡并停止您的应用程序;要么或至少打印其内容 - 以便您了解发生了什么。

并给出您的评论:如果出现错误,您现在永远不会。尤其是在做IO的时候,各种事情都可能出错。请相信我:empty catch blocks 是 bad 实践;而且你不应该训练自己去接受它们。

再三考虑:暂时不要这样做。听起来很方便;但此时保存背景图片并没有增加多少价值。

您无需担心此代码;当您的应用程序出现时,它会执行一次。

所以,真正的答案在这里:关注你想要实现的功能;并且不要因 pre-mature optimizations.

而分心

This I would like to save as a BufferedImage,

不知道您需要将 BufferedImage 保存到文件中。您可以只创建一个 BufferedImage 以供应用程序启动时使用。如果任何用户颜色发生变化,您可以重新创建 BufferedImage。

您可以直接绘制到 BufferedImage:

BufferedImage image = new BufferedImage(boardSize, boardSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();

// draw the squares onto board

g2d.dispose();

现在您的 createBoard() 方法应该 return BufferedImage 以便您的应用程序可以使用它。