【问题标题】:Applet image missing小程序图像丢失
【发布时间】:2011-09-01 11:53:37
【问题描述】:

大家好,Stackoverflow 成员,

CatchTheCreature Applet 类应该显示在不同位置重新绘制的图像,但由于某种原因,该图像没有显示。

  import java.awt.Color;
  import java.awt.Graphics;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.awt.event.MouseEvent;
  import java.awt.event.MouseListener;
  import java.util.Random;

  import javax.swing.ImageIcon;
  import javax.swing.JApplet;
  import javax.swing.Timer;

  public class CatchTheCreature extends JApplet {

private int height = 300;
private int width = 600;
private final int delay = 1001;

private ImageIcon image;
private Timer timer;
private int x, y;
private int counter = 0;
Random gn = new Random();

public void init() {
    DotListener dot = new DotListener();
    addMouseListener(dot);

    image = new ImageIcon("Monster.png");

    timer = new Timer(delay, new timerListener());
    x = 40;
    y = 40;
    getContentPane().setBackground(Color.black);

}

// Action Listener Methods
private class timerListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {

        x = gn.nextInt(width);
        y = gn.nextInt(height);

        repaint();
    }

}

private class DotListener implements MouseListener {

    public void mousePressed(MouseEvent event) {

    }

    @Override
    public void mouseClicked(MouseEvent event) {
        if (event.getX() > (x) && event.getX() < (x + 60)
                && event.getY() < (y + 60) && event.getY() > (y)) {
            x = gn.nextInt(width);
            y = gn.nextInt(height);
            counter = counter + 1;
            repaint();
        }
    }

    @Override
    public void mouseEntered(MouseEvent event) {

    }

    @Override
    public void mouseExited(MouseEvent event) {

    }

    @Override
    public void mouseReleased(MouseEvent event) {

    }

}

public void paint(Graphics g) {
    super.paint(g);
    g.setColor(Color.yellow);
    image.paintIcon(this, g, x, y);
    g.drawString("Clicked accuratly: " + counter, 5, 15);
}

public void start() {
    timer.start();

}

public void stop() {
    timer.stop();
}

}

这是我的html文件

     <applet code = CatchTheCreature width = 250 height = 300>

     </applet>

如果有人能告诉我如何在小程序上显示图像图标,我将不胜感激。

谢谢

【问题讨论】:

    标签: java html image applet imageicon


    【解决方案1】:

    ..image = new ImageIcon("Monster.png");

    • ImageIcon 的基于String 的构造函数假定String 代表File
    • 沙盒小程序无法访问File 对象,但可以访问来自同一代码库/文档库的URLs。
    • 使用getDocumentBase()/getCodeBase() 与图像的相对路径,小程序将是可移植的(假设图像也上传到同一位置)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-20
      • 2021-09-30
      • 2012-01-08
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      相关资源
      最近更新 更多