Results 1 to 2 of 2

Thread: image in jPanel

  1. #1
    idi
    idi is offline Member
    Join Date
    Feb 2010
    Posts
    5
    Rep Power
    0

    Default image in jPanel

    I am trying to display an image loaded from a file in Jpanel. everything seems to be right but it is not displaying it when i select the file :confused:

    Here is my code
    Java Code:
     panel = new ImagePanel();
       jPanel1.add(panel);
       jPanel1.setVisible(true);
    panel.setVisible(true);
    
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
    public boolean accept(File f) {
    String name = f.getName().toLowerCase();
    return name.endsWith(".jpg")|| name.endsWith(".jpeg") || f.isDirectory();}
    
    public String getDescription() {
    return "Image files";
    }});
    int r = chooser.showOpenDialog(this);
    if (r == JFileChooser.APPROVE_OPTION) {
    String name = chooser.getSelectedFile().getAbsolutePath();
    panel.loadImage(name);
        
    }
        }                                        
    
    class ImagePanel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (image != null)
    g.drawImage(image, 0, 0, null);
    }
    
    public void loadImage(String name) {
    Image loadedImage = Toolkit.getDefaultToolkit().getImage(name);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(loadedImage, 0);
    try {
    tracker.waitForID(0);
    } catch (InterruptedException e) {
    }
    image = new BufferedImage(loadedImage.getWidth(null), loadedImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.drawImage(loadedImage, 0, 0, null);
    repaint();}}

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,197
    Rep Power
    19

Similar Threads

  1. How to put an image on a JPanel
    By syferite in forum AWT / Swing
    Replies: 1
    Last Post: 01-20-2010, 05:39 PM
  2. How can I add image to a JPanel using netbeans
    By shahid0627 in forum AWT / Swing
    Replies: 5
    Last Post: 09-01-2009, 07:56 AM
  3. Add Image to JPanel
    By Seonix in forum AWT / Swing
    Replies: 1
    Last Post: 08-12-2009, 01:54 PM
  4. Image appear at random co-ord within jpanel
    By IHateNetbeans in forum New To Java
    Replies: 1
    Last Post: 04-30-2009, 07:06 PM
  5. how to set image to a jpanel
    By masa in forum AWT / Swing
    Replies: 1
    Last Post: 03-02-2009, 08:36 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •