简体   繁体   中英

Java Applet in JFrame image not Showing UP

I wrote this code in JFrame + Applet for a Game.

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();
    }
}

I cannot see the Image showing up as.jpg.
I wanted to Import this Image as a player sprite. My code is not giving any errors, it just not showing the image.

1) You forget to call init() method of your Applet, because of your Image doesn't initialized.

2)Use BufferedImage for your image, load that like next:

public void init() {
    url = getClass().getResource("as.jpeg");
    try {
        player = ImageIO.read(url);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3) add k.init(); before k.start(); in your main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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