[Java] Loading Images

Started by
8 comments, last by rip-off 13 years, 6 months ago
I am trying to load an image but I am receiving two errors, cannot find symbol on Class URL, also cannot find symbol variable image.
import javax.swing.*;import java.awt.*;import java.awt.Toolkit;import java.awt.Image;class ImageLoader extends JComponent{	public void ImageLoader()	{		Toolkit toolkit = Toolkit.getDefaultToolkit();		URL file = getClass().getResource("test.jpeg");		Image image = toolkit.getImage(file);			}		public void paintComponent(Graphics g)	{		int x = 0;		int y = 0;		g.drawImage(image,x,y,this);	}}
Advertisement
import java.net.URL and move Image image outside of the constructor, making it a class member variable.
Can you post the full compiler output? You will need to make "Image image" a field, otherwise it will not work, and you should delete the "void" return type in the constructor definition, constructors do not have a return type. But the compiler should be able to parse that...
Alright I got that working, but when I load the program the image does not show up.

Here is the main part.
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Paravola{	public static void main(String[] args)	{		JFrame frame = new JFrame("Paravola Outbreak");		frame.add(new ImageLoader2());		frame.setSize(640,480);		frame.setResizable(false);		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		frame.setVisible(true);	}}


and here is the fixed code.
import javax.swing.*;import java.awt.*;import java.awt.Toolkit;import java.awt.Image;import java.net.*;class ImageLoader2 extends JComponent{	URL file;	Image image;	public void ImageLoader2()	{		Toolkit toolkit = Toolkit.getDefaultToolkit();		file = getClass().getResource("test.jpg");		image = toolkit.getImage(file);			}		public void paintComponent(Graphics g)	{		int x = 0;		int y = 0;		g.drawImage(image,x,y,this);	}}
Like rip-off said, remove the 'void' before the constructor.
Ok. Thanks for all of your help.
Now with this how would I go about loading an image then having repaint load a different image?
Are you trying to display an animation? Loading an image during repaint will be non-deterministic as swing will take efforts to avoid needlessly repainting the screen.

Anyway, in general you want to avoid image loading at runtime as it is slow. Instead load any images you need at the start - unless there are too many of them, or they are extremely large.
Yes, right now I am trying to load a small animation into my application.
Searching Google for animations in swing gives several promising results.

This topic is closed to new replies.

Advertisement