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...
For your ImagePanel
class
super.paint[Component]
before all the other stuff. paint
but instead paintComponent
paintComponent
method ie setOpaque()
. Beside, JPanel
is opaque by defaultgetPreferredSize()
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
Change your file structure
ProjectRoot
src
images
3D.jpg
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
icon
See related and maybe related