how to add an image to Jpanel

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • momotaro
    Contributor
    • Sep 2006
    • 357

    how to add an image to Jpanel

    Hi everyone,

    I have my Jpanel created using netbeans wizard (drag and drop) and I have my class ImageLoader which prepare the image but am stuck at how I make the image to show on my panel...
    here is the code for ImageLoader:
    Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package myphotoshop.logic;
    
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    
    /**
     *
     * @author AYACH MOHAMED
     */
    public class ImageLoader extends JPanel{
        
        private BufferedImage image;
    
        public ImageLoader(String imageName) {
           try {
                image = ImageIO.read(new File(imageName));
              
              
           } catch (IOException ex) {
                // handle exception...
               System.out.println("lol");
           }
        }
    
        @Override
        public void paintComponent(Graphics g) {
            g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
    
        }
    }
    Here is the code to chose the file :
    Code:
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            
            FileDialog fileChoser = new FileDialog(this);
            fileChoser.setVisible(true);
            
            ImageLoader loadimage = new ImageLoader(fileChoser.getDirectory() 
                                                    + fileChoser.getFile());  
        }
    And here is the generated code for the Jpanel by netbeans:
    Code:
    Panel = new javax.swing.JPanel();
    
    Panel.setBackground(new java.awt.Color(255, 255, 255));
    
    // Code of sub-components - not shown here
    
    // Layout setup code - not shown here
    
    // Code adding the component to the parent container - not shown here
    please help thank's in advance.
Working...