在Java中将图像加载到背景中
问题描述:
如何在Java中将图像加载到背景中?我尝试了许多不同的方法,但没有一个起作用,所以我问是否有人知道如何将png图像上传到jpannel中
How do you load an image into a background in Java? I have tried many different methods and none of them work so I am asking if anyone knows how to upload a png image into a jpannel
答
制作自己的JPanel.在GUI的构造函数中添加PicPanel对象.
Make your own JPanel. Add an object of PicPanel in your GUI's constructor.
class PicPanel extends JPanel{
private BufferedImage image;
private int w,h;
public PicPanel(String fname){ //Pass picture's filename as a parameter.
//reads the image
try {
image = ImageIO.read(getClass().getResource("/"+fname));
w = image.getWidth();
h = image.getHeight();
} catch (IOException ioe) {
System.out.println("Could not read in the pic");
//System.exit(0);
}
}
public Dimension getPreferredSize() {
return new Dimension(w,h);
}
//this will draw the image
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}