java 将背景图像添加到 JPanel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15711821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:36:34  来源:igfitidea点击:

Adding a background image to a JPanel

javaimageswingjpanelpaintcomponent

提问by Matthew G

I'm working on building a board game in Java. For the game board itself I was trying to place the image of the board as the background of the entire JPanel, which fills the JFrame. I found a way to do this, but only with the file stored locally, it needs to be able to take the image from the package the GUI is inside as well.

我正在用 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);
    }
}

I've read that using ImageIcon is a good fix, but I don't know how to use it properly.

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

Edit 1 - I found my answer here http://www.coderanch.com/how-to/java/BackgroundImageOnJPanelI also had the picture formatted wrong in my workspace. Thanks for the help

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

采纳答案by MadProgrammer

  1. Make sure the resource you want to load is located within the Jar file
  2. Use getClass().getResource("/path/to/resource")to obtain a URLreference to the resource, which can be used by ImageIOto read the resource
  1. 确保您要加载的资源位于 Jar 文件中
  2. 使用getClass().getResource("/path/to/resource")以获得URL所述资源,其可以通过使用参考ImageIO读取资源

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

因此,例如,如果图像位于 Jar 内的 /images 文件夹中,则可以使用

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

For example...

例如...