-1

I'm a beginner in Java and I would like to load an image with this script:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
 */
public class LoadImageApp extends Component {

BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImageApp() {
   try {
       img = ImageIO.read(getClass().getResource("/resources/java.png"));//cannot found image
   } catch (IOException e) {
   }

}

public Dimension getPreferredSize() {
    if (img == null) {
         return new Dimension(100,100);
    } else {
       return new Dimension(img.getWidth(null), img.getHeight(null));
   }
}

public static void main(String[] args) {

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp());
    f.pack();
    f.setVisible(true);
}
}

Then I put a picture on a folder resource "resources", change the name of the location of the picture like "/resources/java.png" and when I compile, there is an empty window without image.

You can see error here : https://ibb.co/ysjNyQw

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Axel
  • 15
  • 5
  • `ImageIO.read(getClass().getResource("/resources/java.png"))` – MadProgrammer Feb 02 '19 at 23:20
  • Thanks but , i have got that : Exception in thread "main" java.lang.IllegalArgumentException: input == null! at javax.imageio.ImageIO.read(Unknown Source) at tst.LoadImageApp.(LoadImageApp.java:54) at tst.LoadImageApp.main(LoadImageApp.java:78) – Axel Feb 02 '19 at 23:24
  • this is the problem https://ibb.co/ysjNyQw – Axel Feb 02 '19 at 23:28
  • Since "resources" is called "Resources", you may need to either rename it or change your code to reflect it. You may also want to read up on "embedded resources", [for example](https://stackoverflow.com/questions/3721706/embedding-resources-images-sound-bits-etc-into-a-java-project-then-use-those) – MadProgrammer Feb 02 '19 at 23:36
  • I renamed and replace the code with 'code'public LoadImageApp() { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("Resources/java.png"); // ... } finally { } } 'code' and a empty windows opened without image – Axel Feb 02 '19 at 23:54
  • like this : https://ibb.co/9wpb6sd – Axel Feb 02 '19 at 23:57

1 Answers1

0

The first thing you're going to want to do is do some research into "embedded resources", for example

I don't use Eclipse, I use Netbeans, but the process should be the same

Project

As you can see, I've placed my image in the resources package within the projects "sources". This will ensure that it's available at runtime via the class path search mechanism (and embedded within the resulting Jar file when I export it).

I then used a JLabel to display it...

Example image

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    BufferedImage image = ImageIO.read(getClass().getResource("/resources/java.png"));
                    JLabel label = new JLabel(new ImageIcon(image));

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}

Now, if you want to continue using a custom painting route, I suggest having a read of:

to get a better understanding of how painting works in Swing and how you should work with it

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks it's working. I just don't understand on the main section why you can lauch the objet without a name like this : Test c1 = new Test(); I use to do like that and then c1.method . Why new Test() works without variable? – Axel Feb 03 '19 at 01:21
  • `new Test()` is calling the classes constructor, see `public Test()` – MadProgrammer Feb 03 '19 at 01:29