Displaying ImageIcon
I am trying to display an image on a JPanel
. I am using ImageIcon
to render an image and the image is in the same directory as the class file. However, no image is displayed and no errors occur. Can anyone help design what is wrong with my code ...
package ev;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Image extends JPanel {
ImageIcon image = new ImageIcon("peanut.jpg");
int x = 10;
int y = 10;
public void paintComponent(Graphics g) {
super.paintComponent(g);
image.paintIcon(this, g, x, y);
}
}
source to share
This is a common confusion among programmers.
getClass().getResource(path)
loads resources from the classpath.
ImageIcon image = new ImageIcon("peanut.jpg");
If we only specify the name of the image file, then Java looks for it in the current working directory. If you are using NetBeans, CWD is the project directory. You can compute the CWD at runtime with the following call:
System.out.println(new File("").getAbsolutePath());
Below is a sample code where you can test it yourself.
<Preliminary>package com.zetcode;
import java.awt.Dimension;
import java.awt.Graphics;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class DrawingPanel extends JPanel {
private ImageIcon icon;
public DrawingPanel() {
loadImage();
int w = icon.getIconWidth();
int h = icon.getIconHeight();
setPreferredSize(new Dimension(w, h));
}
private void loadImage() {
icon = new ImageIcon("book.jpg");
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
icon.paintIcon(this, g, 0, 0);
}
}
public class ImageIconExample extends JFrame {
public ImageIconExample() {
initUI();
}
private void initUI() {
DrawingPanel dpnl = new DrawingPanel();
add(dpnl);
// System.out.println(new File("").getAbsolutePath());
pack();
setTitle("Image");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame ex = new ImageIconExample();
ex.setVisible(true);
}
});
}
}
The following figure shows where to put the book.jpg in NetBeans if we only specify the name of the image to the constructor
ImageIcon
.
We have the same command line program. We are located inside the ImageIconExample directory.
$ pwd / home / vronskij / prog / swing / ImageIconExample $ tree ... ├── book.jpg └── com └── zetcode ├── DrawingPanel.class ├── ImageIconExample $ 1.class ├── ImageIconExample.class └── ImageIconExample.java 2 directories, 5 files
The program starts with the following command:
$ ~/bin/jdk1.7.0_45/bin/java com.zetcode.ImageIconExample
You can find out more at my Displaying an Image in Java .
source to share