• Advertisement
Sign in to follow this  

[Java] Loading Images

This topic is 2703 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
}
}


Share this post


Link to post
Share on other sites
Advertisement
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...

Share this post


Link to post
Share on other sites
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);
}
}

Share this post


Link to post
Share on other sites
Now with this how would I go about loading an image then having repaint load a different image?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Yes, right now I am trying to load a small animation into my application.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement