Rajdeep Rajdeep - 6 months ago 14
Java Question

No image displayed using ImageIcon() on the JPanel

Whenever this code is compiled it works fine upto the file choosing option but at the line

ImageIcon ic = new ImageIcon(sname)
it's shows a NullPointerException. I have checked it with a print statement. The variable sname receives the correct path but fails to display the image.

Here is the code:

package Interface;

import java.awt.Component;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;


/**
*
* @author Rajdeep
*/
public class InputPage2 extends javax.swing.JFrame {

/**
* Creates new form InputPage2
*/
public InputPage2() {
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() {

fileChooser = new javax.swing.JFileChooser();
panel = new javax.swing.JPanel();
gray = new javax.swing.JButton();
filter = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Open = new javax.swing.JMenuItem();
Exit = new javax.swing.JMenuItem();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 576, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 652, Short.MAX_VALUE)
);

gray.setText("Gray Scale");
gray.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
grayActionPerformed(evt);
}
});

filter.setText("Filter");
filter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
filterActionPerformed(evt);
}
});

jMenu1.setText("File");

Open.setText("Open");
Open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
OpenActionPerformed(evt);
}
});
jMenu1.add(Open);

Exit.setText("Exit");
Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitActionPerformed(evt);
}
});
jMenu1.add(Exit);

jMenuBar1.add(jMenu1);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(gray, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(filter, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(165, 165, 165)
.addComponent(gray, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(156, 156, 156)
.addComponent(filter, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap(16, Short.MAX_VALUE)
.addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);

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

private void OpenActionPerformed(java.awt.event.ActionEvent evt)throws java.lang.NullPointerException {
// TODO add your handling code here:
fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File file=fileChooser.getSelectedFile();
String sname= file.getAbsolutePath();
sname= "/" +sname;
System.out.println(sname);
ImageIcon ic = new ImageIcon(sname);
JLabel j= new JLabel("",ic,JLabel.CENTER);
panel.add(j);
panel.revalidate();
panel.repaint();
}


}

private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}

private void grayActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("In Gray");
}

private void filterActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("In Filter");
}


/**
* @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(InputPage2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InputPage2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InputPage2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InputPage2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new InputPage2().setVisible(true);
}
});
}


// Variables declaration - do not modify
private javax.swing.JMenuItem Exit;
private javax.swing.JMenuItem Open;
private javax.swing.JFileChooser fileChooser;
private javax.swing.JButton filter;
private javax.swing.JButton gray;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel panel;
// End of variables declaration
}

Answer

The JLabel should be added when the GUI is constructed. Then the code is easy.

private void OpenActionPerformed(java.awt.event.ActionEvent evt)throws java.lang.NullPointerException {
    fileChooser = new JFileChooser();
    int result = fileChooser.showOpenDialog(null);
    if(result == JFileChooser.APPROVE_OPTION){
        File file=fileChooser.getSelectedFile();
        ImageIcon ic = new ImageIcon(file.toURI().toURL());
        j.setIcon(ic);
    }
    // ..

Note: Please learn common Java naming conventions (specifically the case used for the names) for class, method & attribute names & use them consistently. OpenActionPerformed should be openActionPerformed.

Comments