Fiddle Freak
Fiddle Freak

Reputation: 2041

Assign file to image compile error: javax.imageio.IIOException

I'm trying to assign an image as a background with swing. I've found multiple ways to do this, but I always seem to run into the same problem. I found a nice custom class to use here > http://www.camick.com/java/source/BackgroundPanel.java

Here is the code I'm using...

Edit Code: Added Constructor

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;

public class TestMain {
    TestMain(){
        JFrame frame = new JFrame("Test");
        Image img = null;
        File f = new File("../images/Background.png");
        img = ImageIO.read(getClass().getResource(f));
        System.out.println("File " + f.toString());


        BackgroundPanel background = new BackgroundPanel(img, BackgroundPanel.SCALED, 0.50f, 0.5f);

        frame.setContentPane(background);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 100);
        frame.setVisible(true);
    }

    public static void main(String[] args) throws IOException{
        new TestMain();
    }
}

And here is what the image looks like...

enter image description here

When I try to run this code, I get a compile error Error:(14, 51) java: incompatible types: java.io.File cannot be converted to java.lang.String. If anyone could figure out how to help me do this, it would be much appreciated.

Upvotes: 0

Views: 119

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

In the same project, this is the line of code I'm using to make the image show up for a label (same location), and it works > charImgLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource(image)).getImag‌​e().getScaledInstanc‌​e(100, 100, "../images/Character.png".SCALE_SMOOTH)));

Okay, let's just look past the obvious compiler error there for a second.

I assume that image is a String reference to the path of the image within the current classloader context, meaning that

img = ImageIO.read(f);

should actually be

img = ImageIO.read(getClass().getResource(image));

Assuming that the image is stored within the classloader context (ie the Jar/classpath) and the path you've specified is correct, then this should load your image

Upvotes: 1

Related Questions