2014-03-19 64 views
0

無論何時編譯此代碼,它都可以正常使用文件選擇選項,但在行ImageIcon ic = new ImageIcon(sname)處顯示NullPointerException。我用打印聲明檢查了它。變量sname接收正確的路徑,但無法顯示圖像。在JPanel上沒有使用ImageIcon()顯示的圖像

下面是代碼:

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     
} 
+0

爲什麼使用'sname =「/」+ sname;'? 'sname'已經是'File'的絕對路徑表示了?考慮使用'ImageIO.read(file)'而不是... – MadProgrammer

+0

這只是爲了確認實際路徑。該程序運行良好,沒有行 – Rajdeep

回答

2

JLabel應的GUI被構造時加入。那麼代碼很簡單。

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); 
    } 
    // .. 

注:請學會共同Java naming conventions類,方法&屬性名稱&一致地使用它們(特別是用於名稱的情況下)。 OpenActionPerformed應該是openActionPerformed

+0

當然我會記住這一點。 – Rajdeep

+0

非常感謝先生。像魅力一樣工作。 – Rajdeep