Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Java and Images

$
0
0
The subject just eludes me. In various projects that I've worked on for school, I have used several different methods for using images in Java. However, this time, none of the methods I've used prior and nothing I've seen during my searches on Google is working.

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

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
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!

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>