java - 在 JPanel 上使用 ImageIcon() 没有显示图像

标签 java swing

每当编译此代码时,它都能正常工作到文件选择选项,但在 ImageIcon ic = new ImageIcon(sname) 行,它显示 NullPointerException。我已经用打印语句检查过了。变量sname接收到正确的路径但无法显示图像。

这是代码:

    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                   
}

最佳答案

构建 GUI 时应添加 JLabel。那么代码就很简单了。

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

关于java - 在 JPanel 上使用 ImageIcon() 没有显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22498021/

相关文章:

java - 有没有一种方法可以覆盖 JLabel 的内容

多层上下文中的 Swing 富客户端

JAVA Selenium - 在循环中从 html 获取 href

java - 继承强制编译错误

java - 绕过 'Cannot refer to a non-final variable inside an inner class defined'

java - 在所有可达顶点中找到最有值(value)的顶点

java - 使用 SLF4J 桥接 JUL 不起作用

java - 如何制作像 JOptionPane.showMessageDialog(xxx ,"xxx") 这样的函数?

java - 用 Java 显示文本的最佳实践?

java - 如何设置 JRadioButton 的位置?