[英]trouble making background image for a Panel
I am trying to add a background image to a JPanel. 我正在尝试将背景图像添加到JPanel。 The paint Component doesn't seem to paint the image imported for the background .
绘制组件似乎不会绘制为背景导入的图像。 Could anyone point out why?
谁能指出原因? I have imported all the necessary libraries.
我已经导入了所有必需的库。
public class ImagePanel extends JPanel {
public static BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("cards/background.png"));
System.out.println("Image Import Succesful");
} catch (IOException ex) {
System.out.println("IMAGE IMPORT ERROR");
}
ImageIcon icon = new ImageIcon(image);
icon.setImage(image);
JLabel imageLabel = new JLabel(icon);
add(imageLabel);
}
@Override
protected void paintComponent(Graphics g) {
System.out.println("painted");
super.paintComponent(g);
g.drawImage(image, 100, 100,
this);
}
}
Where are you loading your image from? 您从哪里加载图片? A file system or classpath ?
文件系统还是类路径 ?
If you are loading you image from classpath you can use the class loader to load the image.If you are loading the image from a file system the path to that file has to be an absolute path. 如果要从类路径中加载图像,则可以使用类加载器来加载图像。如果要从文件系统中加载图像,则该文件的路径必须是绝对路径。
You can paint the background of a panel if you are loading the image from classpath like this: 如果要从classpath加载图像,则可以绘制面板的背景,如下所示:
public class ImagePanel extends JPanel {
private ImageIcon imageIcon;
public ImagePanel() {
prepareBackground();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (null!= imageIcon)
g.drawImage(image.getImage(), 100, 100, this);
else
System.err.println("Background image is NULL!!");
}
}
private void prepareBackground() {
final java.net.URL imgURL = ImagePanel.class.getResource("cards/background.png");
imageIcon = new ImageIcon(imgURL);
}
}
If you are loading from a file system , you can correct your code here: 如果要从文件系统加载,则可以在此处更正代码:
image = ImageIO.read(new File("COMPLETE_PATH_TO_background.png"));
图片= ImageIO.read(新文件(“ COMPLETE_PATH_TO_background.png”));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.