Reputation: 31
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.
Upvotes: 2
Views: 881
Reputation: 324128
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.
Upvotes: 3
Reputation: 24998
There are a couple of different ways in which you can read images.
ImageIcon
and then extracting the Image
from it.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) {
}
Upvotes: 2