I was hoping that some of the more intermediate to advanced Java programmers can show me how to properly utilize images with Java. More specifically, I would like to be able to show an image within a JPanel (or custom panel that extends JPanel). My issue is that no matter how many searches on Google I do, and no matter how many approaches I try, I can't seem to get images to work easily.
Here's some code that I tried to use to test using images (because I was being driven crazy trying to get them to work from within my current project).
package testimages;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestImageProgram extends JFrame{
BufferedImage image;
public TestImageProgram(){
super("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
image = ImageIO.read(getClass().getResource("imagefile.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
ImagePanel ip = new ImagePanel();
setSize(600, 400);
ip.setVisible(true);
getContentPane().add(ip);
setVisible(true);
}
public static void main(String[] args){
new TestImageProgram();
}
public class ImagePanel extends JPanel{
public ImagePanel() {
JLabel picLabel = null;
if (image == null){
System.out.println("ERROR");
}else{
picLabel = new JLabel(new ImageIcon(image));
}
this.add(picLabel);
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
}
}
This gives me an exception:
Quote
at javax.imageio.ImageIO.read(Unknown Source)
at testimages.TestImageProgram.<init>(TestImageProgram.java:20)
at testimages.TestImageProgram.main(TestImageProgram.java:34)
Just as a note, I put the image file in almost every directory within the project because I'm not sure which directory is considered the "root". However, it doesn't matter because it still doesn't work!

New Topic/Question
Reply



MultiQuote






|