1

trying to get an image to print into a window. Everything runs without errors, and it also works if I replace the drawImage with another graphics class. However, the window is missing the image, and i'm not sure why. Again, the JFrame stuff and Graphics work fine with drawing other graphics, but only doesn't draw the image here. Thanks.

import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.imageio.*;
import javax.imageio.stream.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

public class GraphicsMovement2 extends JApplet{
    BufferedImage image = null;

    public static void main(String args[]){
        BufferedImage image = null;
        try {
            File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
            ImageInputStream imgInpt = new FileImageInputStream(file);
            image = ImageIO.read(file);
        }
        catch(FileNotFoundException e) {
            System.out.println("x");
        }
        catch(IOException e) {
            System.out.println("y");
        }


        JApplet example = new GraphicsMovement2();
        JFrame frame = new JFrame("Movement");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(example);
        frame.setSize(new Dimension(1366,768));       //Sets the dimensions of panel to appear when run
        frame.setVisible(true);
    }
    public void paint (Graphics page){
    page.drawImage(image, 100, 100, 100, 100, Color.RED, this);
  }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jonheel
  • 33
  • 1
  • 5

3 Answers3

7

You've defined image twice...

BufferedImage image = null;

public static void main(String args[]){
    BufferedImage image = null;

This essentially means that by the time you get to the paint method, it is null as you haven't initialized the instance variable.

Another problem you will have is the fact that you are trying to load the image from a static reference but the image isn't declared as static. Better to move this logic into the constructor or instance method.

Don't use JApplet as your container when you're adding to a JFrame, you're better of using something like JPanel. It will help when it comes to adding things to the container.

YOU MUST CALL super.paint(g)...in fact, DON'T override the paint method of top level containers like JFrame or JApplet. Use something like JPanel and override the paintComponent method instead. Top level containers aren't double buffered.

The paint methods does a lot of important work and it's just easier to use JComponent#paintComponent ... but don't forget to call super.paintComponent

UPDATED

You need to define image within the context it is going to be used.

Because you declared the image as an instance field of GraphicsMovement2, you will require an instance of GraphicsMovement2 in order to reference it.

However, in you main method, which is static, you also declared a variable named image.

The paint method of GraphicsMovement2 can't see the variable you declared in main, only the instance field (which is null).

In order to fix the problem, you need to move the loading of the image into the context of a instance of GraphicsMovement2, this can be best achived (in your context), but moving the image loading into the constructor of GraphicsMovement2

public GraphicsMovement2() {
    try {
        File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
        ImageInputStream imgInpt = new FileImageInputStream(file);
        image = ImageIO.read(file);
    }
    catch(FileNotFoundException e) {
        System.out.println("x");
    }
    catch(IOException e) {
        System.out.println("y");
    }
}

The two examples below will produce the same result...

enter image description here

The Easy Way

public class TestPaintImage {

    public static void main(String[] args) {
        new TestPaintImage();
    }

    public TestPaintImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePane extends JPanel {

        public ImagePane() {
            setLayout(new BorderLayout());
            ImageIcon icon = null;
            try {
                icon = new ImageIcon(ImageIO.read(new File("/path/to/your/image")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            add(new JLabel(icon));
        }

    }
}

The Hard Way

public class TestPaintImage {

    public static void main(String[] args) {
        new TestPaintImage();
    }

    public TestPaintImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage background;

        public ImagePane() {
            try {
                background = ImageIO.read(new File("/path/to/your/image"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (background != null) {
                int x = (getWidth() - background.getWidth()) / 2;
                int y = (getHeight() - background.getHeight()) / 2;
                g.drawImage(background, x, y, this);
            }
        }
    }
}

Take the time to read through the tutorials

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • That answer was a bit beyond me, do i put the 'BufferedImage image = null;' in the main method or not? I tried to not do it earlier but like you said I had problems with it being declared as static. – Jonheel Nov 02 '12 at 02:47
  • Thanks for the fully detailed fixes for both. Seeing both definitely changed my attitude on this. My last question before i can mark this as solved is whether I should put the ImagePane class into a new .java file. Everything else at least builds right now, and looks better too. – Jonheel Nov 02 '12 at 21:13
  • @Jonheel The `ImagePane` in my example should be completely independent, and from a reuse point of view, yes, it can be in it's own source file – MadProgrammer Nov 02 '12 at 21:19
  • Thank you, its just what I wanted. The stuff in graphics are still a bit above me, even after this, so when i do return to graphics, I will be sure to refer back to this. – Jonheel Nov 02 '12 at 21:23
2

Your class shouldn't extend JApplet when you're not even using applets -- this makes no sense. Instead

  • Have your drawing class extend JPanel
  • Draw in the JPanel's paintComponent method
  • Add this JPanel to the JFrame's contentPane.
  • Read the Swing painting tutorials. You can't guess at this stuff and expect it to work, and the tutorials will show you how it's done correctly.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Is there not a way to avoid that? Again, even though this may not be the best way to do things, it gets the job done, plus im not expanding on this program after it displays the bufferedImage. – Jonheel Nov 02 '12 at 02:32
  • @user1793082: why try to do things the wrong way for no good reason? Again, it makes no sense. You could use a vice grip to bang in nails, and it would sort of work, but why continue doing this when a hammer is much better suited for the job? – Hovercraft Full Of Eels Nov 02 '12 at 02:34
  • @user1793082 bagging my head against a wall will bring down the wall, but why suffer the pain... – MadProgrammer Nov 02 '12 at 02:36
  • I agree entirely, but i'm trying to limp across the finish line here. I'm not going to return to graphics for a long time after this program, so i'm not looking for a well written program right now. – Jonheel Nov 02 '12 at 02:41
  • @user1793082 *"I'm not going to return to graphics for a long time"* don't limit yourself, you don't know where life will drag you, kicking and screaming ;) – MadProgrammer Nov 02 '12 at 03:04
  • @jonheel: `"so i'm not looking for a well written program right now"`: Not a real great attitude. It almost makes me want to wonder why we should waste time trying to help you when we can instead spend time with a student who cares. Just hope your doctor didn't have this attitude when he was studying medicine. – Hovercraft Full Of Eels Nov 02 '12 at 03:06
  • @MadProgrammer Go figure, I have now spent 10+ hours going through the java swing class tutorials – Jonheel Nov 03 '12 at 14:57
2

Don't mix file deviders,

File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");

should be replaced with:

File file = new File("C:/Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");

Mordechai
  • 15,437
  • 2
  • 41
  • 82
  • Good for saving me one character, but not much else. It didn't help and i had a file reading program from before that worked using the other way. – Jonheel Nov 02 '12 at 02:35