开发者

How to display a BufferedImage in JApplet

No images are displayed on the japplet.

  public void setCharacter(String type)
 {
  try
  {
   character = ImageIO.read(new File(type));
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }

That's how I retrieve the file.

public void paint(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;

  g2.setBackground(Color.BLACK);

  switch (manipulateCase)
  {
   case 0:
    g2.setColor(Color.BLACK);
    g2.fill(new Rectangle(0, 0, xBound, yBound)); // painting the background.
    break;

   case 1:
    normandy.delete(g2); // delete previous position
    ImageIcon stuff = new ImageIcon("spaceship.jpg");
    stuff.paintIcon(this, g2, 0, 0);
    //g2.drawImage(normandy.getImage(), normandy.getBounds().x, normandy.getBounds().y, null); // draw new position
    break;

   /*case 2:
    for (int i = 0; i < aLevel.getInvaders().length; i++) {
     g2.fill(aLevel.getInvaders()[i].getCharacter());
    }
    break;

   case 3:
    g2.setColor(Color.WHITE);

    if (bullets.getBullets().size() > 0)
     for (int i = 0; i < bullets.getBullets().size(); i++) {
      g2.fill(bullets.getBullets().get(i).getBullet());
      System.out.println("BULLETS: "
        + bullets.getBullets().size());
     }
    break;

   case 4:
    brea开发者_C百科k; */
  }

 }

The above code is in the applet.

What am i doing wrong? Why am I getting the error. "Cannot read input file!"

Any help would be appreciated.

Thank you, blargman


Where does the file reside? An applet running in a browser can't read a file on your computer, it can only access it via a URL. It could access a file on the remote computer, but is normally (for a good reason) not allowed to. So replace new ImageIcon(String filename) by new ImageIcon(URL location).


Custom painting should not be done by overriding the paint() method.

Start by reading the section from the Swing tutorial on How to Make Applets for more details on writing an applet. There is also a section on "Loading Images into Applets".

I also agree to learn how to do painting is is easier to just practice with a simple application that uses a JFrame. You can read the section from the Swing tutorial on "Custom Painting" for more examples. The tutorial is full of great information and examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜