javaimageswingnetbeansmatisse

Matisse properly setting image to panel


I got a problem with NetBeans resource managing while setting images to pannel:

This is my not working code:

try {
    BufferedImage myPicture = ImageIO.read(new File("images/3D.jpg"));
    JLabel picLabel = new JLabel(new ImageIcon(myPicture));
    pnlMain.add(picLabel); //the main and only pannel made by matisse is called pnlMain
} catch (IOException e) {
    JOptionPane.showMessageDialog(this, "Cannot set image");
}

The folder called "images" is in the MAIN project folder. There are several folders: build, nbproject, src and "images".
The problem I have is that the program runs but it doesnt set the image...

Someone suggested me to make another class in different package with this code:

public class PanelImage extends JPanel{
private Image imag;

public PanelImage(Image img){
    if(imagen != null){
        this.imagen = img;
    }
}

@Override
public void paint(Graphics g){
    g.drawImage(img, 0,0, getWidth(), getHeight(), this);
    setOpaque(false);
    super.paint(g);
}
}

But i cant find a proper way of implementing it...


Solution

  • For your ImagePanel class

    1. super.paint[Component] before all the other stuff.
    2. Don't override paint but instead paintComponent
    3. Don't set properties in paintComponent method ie setOpaque(). Beside, JPanel is opaque by default
    4. Override getPreferredSize() for painting on panels

    For loadng images

    Make a habit of not reading images from the file system, unless the application is specific to only your machine.

    Instead read from the class path and make the image a resource by packaging it into the class path

    1. Change your file structure

      ProjectRoot
               src
                  images
                       3D.jpg
      
    2. Read from class path. Use ImageIO to make sure your path is correct. If it's invalid, an exception will be thrown

      URL url = getClass().getResource("/images/3D.jpg"); 
      Image image = ImageIO.read(url);
      

    For Netbeans GUI Builder

    You can set the label icon using the design tool

    1. Select your label from the navigator or the design view.
    2. Go to the properties window in the right and find the property icon
    3. click the ellipses button to the right of the property and a dialog will appear.
    4. Find your image and select OK (make sure your image is in a package in the src)

    See related and maybe related