0

The image I am trying to display is not properly displayed.

I am using the ImageIO to read, and paint it afterwards.

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class imagestukje extends JPanel {

    private BufferedImage image;

    public imagestukje() {
        try {
            image = ImageIO.read(new File("images/lingo.jpg"));
        } catch (IOException e) {

        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

Why isn't the image displayed?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
MESP
  • 486
  • 2
  • 17
  • 3
    Don't leave an empty `catch` clause! You don't know if you succeeded in reading the image or not. At least put `e.printStackTrace()` in there. – RealSkeptic Feb 22 '17 at 08:53
  • 2
    I suspect that ImageIO.read is failing, but there is no way to tell since there is nothing in your catch clause to clarify that. – Legatro Feb 22 '17 at 08:59
  • 1
    Where is the image stored in relation to the location from which the code is been executed, based on your example, it should be off the working directory – MadProgrammer Feb 22 '17 at 10:11
  • 1
    Also consider [embedding the resource](http://stackoverflow.com/tags/embedded-resource/info); if this is not a duplicate, please edit your question to include a [mcve] that shows your revised approach. – trashgod Feb 22 '17 at 17:29

2 Answers2

-1

Hi you should use the search before you ask a question which was already solved.

try this:

Community
  • 1
  • 1
M Zippka
  • 93
  • 13
-1

There you may have two problems:

  • size of panel was not defined
  • panel was not repainted

You may improve your panel with following:

public class ImagePanel extends JPanel {
    BufferedImage image;
    Dimension size = new Dimension();

    public ImagePanel() {
    }

    public ImagePanel(BufferedImage image) {
        this.image = image;
        this.size.setSize(image.getWidth(), image.getHeight());
    }

    public void setImage(BufferedImage image) {
        this.image = image;
        this.size.setSize(image.getWidth(), image.getHeight());
    }

    @Override
    protected void paintComponent(Graphics g) {
        if(this.image != null) {
            g.drawImage(this.image, x, y, this);
        }

    }

    @Override
    public Dimension getPreferredSize() {
        return this.size;
    }
}

So after configuring your UI you can initialize that panel with any image like following:

try {
    image = ImageIO.read(new File("images/lingo.jpg"));
    ((ImagePanel) jPanel).setImage(image);

    jPanel.invalidate();
    jPanel.repaint();
} catch (IOException e) {

}