简体   繁体   中英

Why doesn't getImage() return an error or display an image?

I'm trying to use getImage() do display an image on a JPanel in an application I'm writing. I've tried and tried to get this to work for me, and eventually discovered that even when the path is totally incorrect, it still does not work, nor does it return NullPointerException as would be expected.

Image i;    

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(i, 0, 0, 200, 200, this);
} // end paintComponent();

public Pnl() {
    super();
    setBackground(Color.GREEN);
    setBorder(BorderFactory.createLineBorder(Color.GRAY, 10));
    i = Toolkit.getDefaultToolkit().getImage("shrek.jpg");
} // end constructor    

When I run the code with a parameter such as "shrek...jdhhd" in getImage() or something of that sort, it does exactly the same thing.

I'm trying to use getImage() do display an image on a

When you post a question post a proper SSCCE if you want help otherwise we spend time guessing.

For example maybe the image is being read properly but the problem is that the size of your panel is (0, 0) so there is nothing to paint.

You should also be overriding the getPreferredSize() method to return a Dimension of (200, 200) since this is the size you want to paint your image at.

Without a SSCCE that shows the context of how this panel is used we are just guessing.

There are a couple of different ways in which you can read images.

  1. By using ImageIcon and then extracting the Image from it.
  2. Using ImageIO

I suspect a problem with your path to the image. Try this:

Path imgPath = Paths.get("/path/to/image.png");
if(Files.exists(imgPath)){
    // do whatever
} else{

    // incorrect path
}

If the Path does indeed exist:

ImageIcon imageAsIcon = new ImageIcon(imgPath.getAbsolutePath());
Image imageOfIcon = imageAsIcon.getImage();

Now, you can just retrieve its Graphics object and do whatever like maybe convert it into a BufferedImage

You may also try using ImageIO as follows:

BufferedImage img;

try {
    URL url = new URL(new File("/path/to/image.png");
    img = ImageIO.read(url);
} catch (IOException e) {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM