简体   繁体   中英

Adding an Image to JPanel using NetBeans IDE

I am trying to add n image to a panel using Netbeans. I dragged a Panel from the palette on to the frame and sized it according to what I want the image size to be. In the constructor I then added the image to the panel(I named it panelImage) like this.

JLabel label = new JLabel(new ImageIcon("images\\BrokenFrameResized.jpg"));
    paneImage.add(label);

The image however does not display. What is the best way to have the an image displayed as the size of the Panel using Matisse layout manager(iow dragging and dropping the panel).

Is it better to use paintComponent(Graphics g)?.

Is it better to use paintComponent(Graphics g)?.

It is if you want the image to appear behind other components, otherwise display it in a JLabel . The problem here is most likely that you are accessing an embedded application resource as if it were a File . Embedded resources must be accessed via URL .

EG

URL urlToImage = this.getClass().getResource("/images/BrokenFrameResized.jpg");
ImageIcon icon = new ImageIcon(urlToImage);
...

Yeah. You should definitely use the paintComponent. If you try and use a JLabel, it's going to be hard to fit any other components into your panel because Components may not overlap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM