[英]Adding a background image to a JPanel
我正在用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我的工作區中的圖片格式錯誤。 謝謝您的幫助
getClass().getResource("/path/to/resource")
獲取getClass().getResource("/path/to/resource")
的URL
引用, ImageIO
可以使用它來讀取資源 因此,例如,如果圖像位於Jar內的/ images文件夾中,則可以使用
ImageIO.read(getClass().getResource("/images/5x5 Grid.jpg"));
例如...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.