Results 1 to 2 of 2
  1. #1
    trill is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default Help with load image

    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.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    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
    Java Code:
    URL url = getClass().getResource(path);
    Java 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);
        }
    }

Similar Threads

  1. Load URL that contains spaces?
    By barkster in forum Java Applets
    Replies: 0
    Last Post: 01-30-2008, 09:40 PM
  2. Replies: 0
    Last Post: 01-08-2008, 05:29 PM
  3. how to load a lot of files?
    By gabriel in forum Java Servlet
    Replies: 1
    Last Post: 08-07-2007, 06:04 PM
  4. how to load a html document
    By boy22 in forum Java Servlet
    Replies: 1
    Last Post: 08-05-2007, 04:12 AM
  5. Load song according to its Genre
    By ahlai in forum AWT / Swing
    Replies: 1
    Last Post: 07-24-2007, 02:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •