繁体   English   中英

JFrame图像中的Java Applet不显示UP

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM