我正在尝试将图像加载到我的 Java 小程序中,并且我已经尝试了几种方法,但图像仍然没有出现在小程序中。
这是我的代码:
public class BackgroundApplet extends Applet {
Image backGround;
Image fish;
public void init() {
// set the size of the applet to the size of the background image.
// Resizing the applet may cause distortion of the image.
setSize(300,300);
// Set the image name to the background you want. Assumes the image is in
// the same directory as the class file is
backGround = getImage(getCodeBase(),"underwater.jpg");
BackGroundPanel bgp = new BackGroundPanel();
bgp.setLayout(new FlowLayout());
bgp.setBackGroundImage(backGround);
// set the layout of the applet to Border Layout
setLayout(new BorderLayout());
// now adding the panel, adds to the center(by default in Border Layout) of the applet
add(bgp);
fish = getImage(getCodeBase(), "fish.jpg");
}
public void paint(Graphics g)
{
// Attempt 1
g.drawImage(fish,20,20,this);
// Attempt 2
ImageIcon img = new ImageIcon("fish.jpg");
img.paintIcon(this, g, 20,20);
// Attempt 3
Image image = img.getImage();
g.drawImage(image, 50, 50, this);
}}
如您所见,我还将背景图像加载到我的小程序中,并且显示效果很好。难道是鱼在背景图像后面加载?
任何帮助表示赞赏,谢谢!
**无关注意:我实现Runnable接口时(因为我想在背景图上面有动画),运行小程序时背景图突然不出现了。对此也有任何提示吗?