0

This is a very simple problem to some people I'm assuming and I just can't see it. (I'm very amateur at Java).

This is some test code I wrote to try and troubleshoot why it's not working in my other project. For some reason my rocketshipStationary.png just won't show up when I load the Java Applet.

This is my code:

public class Test extends Applet {

    public Image offScreen;
    public Graphics d;
    public BufferedImage rocketship;



    public void init() {
        setSize(854, 480);
        offScreen = createImage(854,480);
        d = offScreen.getGraphics();

        try {
            rocketship = ImageIO.read(new File("rocketshipStationary.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void paint(Graphics g) {
        d.clearRect(0, 0, 854, 480);
        d.drawImage(rocketship, 100, 100, this);
        d.drawImage(offScreen, 0, 0, this);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • What does happen? Do you get any messages on the console? You haven't posted code for `createImage()`; is it painting over the `rocketship` in your `paint()` method? – chrylis -cautiouslyoptimistic- Nov 28 '13 at 05:54
  • 1
    1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. If you need to support older AWT based APIs, see [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Nov 28 '13 at 05:58
  • Have you checked that your electronic thumb is working? – paxdiablo Nov 28 '13 at 06:02
  • 1
    3) `public Graphics d;` Don't store a reference to a `Graphics` object. They are typically transitory. In 10+ years of Java development, I have yet to see a reason for doing so. 4) `setSize(854, 480);` The size of an applet is set in the HTML, the applet code should not try to adjust that. – Andrew Thompson Nov 28 '13 at 06:02
  • I doubt reading the file works. But even if it did.. In paint, you never paint anything to g, you only paint to your own member variable d (from offscreen).. – Harald K Nov 28 '13 at 06:09

1 Answers1

2

You should be getting a nice big stack trace that describes what happens. The bottom line is that 'applets and files do not play well together'.

Instead, either establish an URL to the image and use that for ImageIO, or alternately use the URL in the Applet.getImage(URL) method.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433