Hi, I'm trying to learn Java at the moment and am struggling big time!
Anyways, for the application I'm writing I need to load a background image from a jpg file.
I've tried a few options but nothing seems to work. any suggestions?
Thanks.
Printable View
Hi, I'm trying to learn Java at the moment and am struggling big time!
Anyways, for the application I'm writing I need to load a background image from a jpg file.
I've tried a few options but nothing seems to work. any suggestions?
Thanks.
Yes. There are many ways to load images.
The Class getResource method looks for the "path" on your class path.
If you are not in static context, eg, inside the main method, you could write
Code:URL url = getClass().getResource(path);
Code:import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageLoading {
private JScrollPane getContent(BufferedImage image) {
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
label.setHorizontalAlignment(JLabel.CENTER);
return new JScrollPane(label);
}
public static void main(String[] args) throws IOException {
String path = "images/cougar.jpg";
URL url = ImageLoading.class.getResource(path);
BufferedImage image = ImageIO.read(url);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new ImageLoading().getContent(image));
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}