简体   繁体   English

如何在Eclipse中的Java Applet中显示图像?

[英]How to display an image in a java applet in eclipse?

I'm having trouble displaying an image in an applet in eclipse. 我无法在Eclipse的小程序中显示图像。 I'm wondering if there is any alternate way of doing this. 我想知道是否还有其他替代方法。 I also want to know if there is a reliable online applet tester that displays an applet I made on the web. 我还想知道是否有一个可靠的在线小程序测试器来显示我在网络上制作的小程序。 I'm following the oracle tutorials but they don't work. 我正在关注oracle教程,但它们不起作用。 Here is my code: 这是我的代码:

Displaying class: 显示类:

import java.applet.Applet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;


public class usb extends Applet{
static BufferedImage background;
/**
 * 
 */
private static final long serialVersionUID = 1L;
@Override
public void init() {
    // TODO Auto-generated method stub
    try {
        URL url = new URL(getCodeBase(), "resources/usb_homescreen.png");
        background = ImageIO.read(url);
    } catch (IOException e) {
    }
    setSize(1000,500);
    add(new goat());
}

}

Canvas class: 画布类:

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;


public class goat extends Canvas {

/**
 * 
 */
private static final long serialVersionUID = 1L;
goat() {
    setSize(1000,500);
    setBackground(Color.white);
}

@Override
public void paint(Graphics g) {
    // TODO Auto-generated method stub
    super.paint(g);
    g.drawImage(usb.background, 0, 0, null);
}
}

Any ideas about what's wrong? 有什么问题的想法吗?

Applets are executed in a special environment. 小程序在特殊环境中执行。 When using them as plain objects, this environment is missing, ie the init method will never get called and the method getCodeBase() will not work. 当将它们用作普通对象时,会缺少此环境,即,永远不会调用init方法,并且getCodeBase()方法将不起作用。 If you want to test an Applet there's the program appletviewer.exe shipped with the JDK. 如果要测试Applet ,则JDK附带了appletviewer.exe程序。 It requires a HTML page containing an <applet> or <object> tag. 它需要一个包含<applet><object>标记的HTML页面。

But there is also a way to instantiate an Applet within a stand-alone java application which will generate the required context. 但是,还有一种方法可以在独立的Java应用程序中实例化Applet ,该应用程序将生成所需的上下文。 Given an Applet class “ MyApplet ” the necessary code looks like: 给定一个Applet类“ MyApplet ”,必要的代码如下:

MyApplet applet=(MyApplet)java.beans.Beans.instantiate(
  MyApplet.class.getClassLoader(), MyApplet.class.getName());
System.out.println(applet.getCodeBase());//prove that the context is now there
// now you can use applet like a normal AWT/Swing component

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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