Sign in to follow this  
monp

[Java] Loading Images

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
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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this