[英]Java Applet in JFrame image not Showing UP
我在JFrame + Applet中为游戏编写了这段代码。
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.applet.*;
import java.net.URL;
public class myGame extends Applet {
static myGame k = new myGame();
JFrame f = new JFrame("myGame");
URL url;
Image player;
public void init(){
url = this.getDocumentBase();
player = this.getImage(url,"as.jpeg");//Here is the Image import
}
public void paint(Graphics g){
g.setColor(Color.BLUE);
g.drawString("HI THERE",200,200);
g.fillRect(120,130,50,50);
g.drawImage(player,20,200,this); Here I draw it
}
public void start(){
f.setSize(600,400);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.add(k);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
k.start();
}
}
我看不到图像出现as.jpg。
我想将此图像作为播放器精灵导入。 我的代码没有给出任何错误,它只是没有显示图像。
1)您忘记调用Applet的init()
方法,因为您的Image
未初始化。
2)为您的图像使用BufferedImage
,加载如下:
public void init() {
url = getClass().getResource("as.jpeg");
try {
player = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
}
3)添加k.init();
在k.start();
之前k.start();
在你的main
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.