0

Here is what I got, but when I run the program the image won't show up, the only thing that shows up when I click run is a empty Jpanel. Can Someone please tell me another way of importing image in java or just help me edit my code so that my program works. (P.S the image I am trying to import is a jpg type image) Thanks.

import java.awt.*
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class LoadImageApp extends Component {

BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImageApp() {
   try {
       img = ImageIO.read(new File("example.jpg"));
   } catch (IOException e) {
   }

}

public Dimension getPreferredSize() {
    if (img == null) {
         return new Dimension(600,600);
    } else {
       return new Dimension(img.getWidth(null), img.getHeight(null));
   }
}

public static void main(String[] args) {

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp());
    f.pack();
    f.setVisible(true);
}
}
jack zhang
  • 133
  • 3
  • 3
  • 10
  • The "example.jpg" is where I am going to put the name of the image. – jack zhang Mar 25 '15 at 20:55
  • 1
    It's almost always the path. You need to be sure that you're using the correct path to the image file, same as a million other similar questions. – Hovercraft Full Of Eels Mar 25 '15 at 20:59
  • 1
    Also your question states "JPanel" but you're overriding Component for an unknown (and likely incorrect) reason. Don't do this. Extend JPanel and draw in its `paintComponent` method, or show your image in as an ImageIcon in a JLabel. – Hovercraft Full Of Eels Mar 25 '15 at 21:00

0 Answers0