0

Tecnically, i wanna put an image that is located on my proyect

I have this JPanel

 */
package vista;

import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
 *
 * @author harri
 */
public class scene1 extends javax.swing.JPanel {
    
    String ruta = "src/backgrounds/backgroundmenu.png";

    ImageIcon fot = new ImageIcon(ruta);
    Icon icono = new ImageIcon(fot.getImage().getScaledInstance(this.backgroundscene1.getWidth(), this.backgroundscene1.getHeight(), Image.SCALE_DEFAULT));

    
     

    
    public scene1() {
        initComponents();
        

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        backgroundscene1 = new javax.swing.JLabel();

        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        backgroundscene1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/backgrounds/backgroundmenu.png"))); // NOI18N
        add(backgroundscene1, new org.netbeans.lib.awtextra.AbsoluteConstraints(-3, 2, 1286, 745));
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    public javax.swing.JLabel backgroundscene1;
    // End of variables declaration                   
}

an i have a method that add this Jpnale to another one in a frame, everything is okay because i tested and works, but the problems start when i wanna use this:

ImageIcon fot = new ImageIcon(ruta);
    Icon icono = new ImageIcon(fot.getImage().getScaledInstance(this.backgroundscene1.getWidth(), this.backgroundscene1.getHeight(), Image.SCALE_DEFAULT));

Im getting Nullpointerexception.

So, basically, how can i put an image on a Jpanel and resize it?

  • The reason you are getting `NullPointerException` is because the image path defined in your `ruta` String is wrong. To fetch a resource that is located in the source folder of your project you have to use `getClass().getResource()`. **Solution**: Replace `ImageIcon fot = new ImageIcon(ruta);` with `ImageIcon fot = new ImageIcon(getClass().getResource("/backgrounds/backgroundmenu.png"));` Also, read this post, https://stackoverflow.com/questions/6845231/how-to-correctly-get-image-from-resources-folder-in-netbeans – Miles Morales Jul 31 '20 at 02:14
  • Didn't worked using that method. – Harrison 01233 Jul 31 '20 at 15:24
  • Weird enough! Please edit your question and add the new code and the error you are getting now. – Miles Morales Aug 01 '20 at 04:46

0 Answers0