Hey guys! So, created a File Chooser that gets a picture. And I want the program to display the picture on the jFrame. How can I accomplish this? I'm using NetBeans, and I'm still kinda new to it :P
Thanks guys! :D
Here's my code:

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OpenImage.java
 *
 * Created on Nov 30, 2011, 11:58:57 PM
 */
/**
 *
 * @author Kevin
 */

public class OpenImage extends javax.swing.JFrame {

    /** Creates new form OpenImage */
    public OpenImage() {
        initComponents();
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jToolBar1 = new javax.swing.JToolBar();
        LoadImage = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        RemoveImage = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        Exit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setRollover(true);

        LoadImage.setText("Load an image");
        LoadImage.setFocusable(false);
        LoadImage.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        LoadImage.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        LoadImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoadImageActionPerformed(evt);
            }
        });
        jToolBar1.add(LoadImage);
        jToolBar1.add(jSeparator1);

        RemoveImage.setText("Remove Image");
        RemoveImage.setFocusable(false);
        RemoveImage.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        RemoveImage.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(RemoveImage);
        jToolBar1.add(jSeparator2);

        Exit.setText("Exit");
        Exit.setFocusable(false);
        Exit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        Exit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitActionPerformed(evt);
            }
        });
        jToolBar1.add(Exit);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(355, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

private void LoadImageActionPerformed(java.awt.event.ActionEvent evt) {
   FileFilter ft = new FileNameExtensionFilter("Pictures", ".jpg");
    jFileChooser1.addChoosableFileFilter( ft );

    int returnVal = jFileChooser1.showOpenDialog( this );        
    if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
        
        java.io.File file = jFileChooser1.getSelectedFile( );
        
    }
}

private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OpenImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OpenImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OpenImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OpenImage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new OpenImage().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify
    private javax.swing.JButton Exit;
    private javax.swing.JButton LoadImage;
    private javax.swing.JButton RemoveImage;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration
}

Recommended Answers

All 11 Replies

Thanks for that link! :D But my problem is that I'm not quite sure how to implement that into my code. I'm still kinda new to NetBeans.

Ok, I think I get it.
So, I a select an image file with this:

java.io.File file = jFileChooser1.getSelectedFile( );

The image file is stored in the variable "file".
Then I'll create a jLabel:

JLabel jLabel1 = new JLabel();

and then an ImageIcon:

ImageIcon image = new ImageIcon(file);

Like this?

Yes, somewhat. You can go ahead and put a JLabel in your UI to hold the image and when you want to set or update it, you can call setIcon() to specify the new image icon.

I tried coding it and it doesn't work.

ImageIcon image = new ImageIcon(file);

What's the problem with it?

Check the constructors for ImageIcon. You need to either use the string file path which you can get with file.getPath() or a URL object, which can be obtained from a File with the toURL() method

I'm kinda confused. :/
Does it end up looking like this:

JLabel jLabel1 = new JLabel(image);
        ImageIcon image = new ImageIcon(file.getPath());

No, you can't reference an image you haven't created yet. You must swap those two lines. This is remedial language usage.

Hey guys! I was able to display the picture earlier, but something happened to my laptop and I wasn't able to save :(
Anyway, I forgot what I did and I'm trying to re-trace my steps. Here's the code I got now:

private void LoadImageActionPerformed(java.awt.event.ActionEvent evt) {                                          
int returnVal = jFileChooser1.showOpenDialog( this );        
    if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
        
        File file = jFileChooser1.getSelectedFile( );
            
                
                image = ImageIO.read(file);
                
                ImageIcon image = new ImageIcon(file.getPath());
                jLabel1 = new JLabel(image);
            
      
        
}                                         
}

NetBeans gave me this suggestion for my code:

private void LoadImageActionPerformed(java.awt.event.ActionEvent evt) {                                          
int returnVal = jFileChooser1.showOpenDialog( this );        
    if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
        
        File file = jFileChooser1.getSelectedFile( );
            try {
                image = ImageIO.read(file);
            } catch (IOException ex) {
                Logger.getLogger(OpenImage.class.getName()).log(Level.SEVERE, null, ex);
            }
                
                ImageIcon image = new ImageIcon(file.getPath());
                jLabel1 = new JLabel(image);
            
      
        
}                                         
}

Why are you trying to load 'image' twice? You shouldn't need the ImageIO.read() at all. The ImageIcon should suffice.

You also do not need to create a new label if you already have one placed in your UI. Just call label.setIcon() to set the new image.

agreed with Ezzaral

for safiest way only to add flush method e.g.

myIcon.getImage().flush();

then add Icon to JLabel

myLabel.setIcon(myIcon);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.