View Single Post
  #2 (permalink)  
Old 08-01-2007, 09:16 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
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); } }
Reply With Quote