Reading images imported into NetBeans

27 views Asked by At

I have imported images into my NetBeans project: project file tree

I'm trying to read the image path and want to display them on JLabels using the scaleImage() method.

My code:

public Home() {
    initComponents();
    scaleImage(img1, "/Images/Background_Image.jpg");
}

public void scaleImage(JLabel label, String imagePath) {
    ImageIcon icon = new ImageIcon(getClass().getResource(imagePath));
    Image img = icon.getImage();
    Image imgScale = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
    ImageIcon scaledIcon = new ImageIcon(imgScale);
    label.setIcon(scaledIcon);        
}

However, i keep getting errors java.lang.NullPointerException

I tried another way, but still prompting errors java.lang.IllegalArgumentException: input == null!:

public void scaleImage(JLabel label, String imagePath) {
    try {
        BufferedImage image = ImageIO.read(Home.class.getResource(imagePath));
        Image imgScale = image.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
        ImageIcon scaledIcon = new ImageIcon(imgScale);
        label.setIcon(scaledIcon);
    } catch (IOException e) {
        // Handle any exception that may occur during image loading
        e.printStackTrace();
    }
}

Any better idea? Thanx

1

There are 1 answers

0
thevalidator On

Try to create the resources folder (src/main/resources) and put there your folder Image with the image file, I think this is the main problem. If it doesn't help try to use Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Images/Background_Image.jpg")) to get the image