7

我正在用 Java 构建棋盘游戏。对于游戏板本身,我试图将板的图像放置为整个 JPanel 的背景,它填充了 JFrame。我找到了一种方法来做到这一点,但只有本地存储的文件,它还需要能够从 GUI 所在的包中获取图像。

package Gui;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

//Proof of concept for setting an image as background of JPanel

public class JBackgroundPanel extends JPanel {
    private BufferedImage img;

    public JBackgroundPanel() {
        // load the background image
        try {
            img = ImageIO.read(new File(
                    "C:\\Users\\Matthew\\Desktop\\5x5     Grid.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // paint the background image and scale it to fill the entire space
        g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
    }
}

我读过使用 ImageIcon 是一个很好的解决方法,但我不知道如何正确使用它。

编辑 1 - 我在这里找到了答案 http://www.coderanch.com/how-to/java/BackgroundImageOnJPanel 我的工作区中的图片格式也有误。谢谢您的帮助

4

1 回答 1

6
  1. 确保要加载的资源位于 Jar 文件中
  2. Use getClass().getResource("/path/to/resource") to obtain a URL reference to the resource, which can be used by ImageIO to read the resource

So, for example, if the image was located in the /images folder inside your Jar, you could use

 ImageIO.read(getClass().getResource("/images/5x5    Grid.jpg"));

For example...

于 2013-03-29T21:46:40.567 回答