Java 如何修复空指针异常

Java 如何修复空指针异常,java,swing,user-interface,jframe,actionlistener,Java,Swing,User Interface,Jframe,Actionlistener,我正在尝试用Java开发一个图像编辑器,目前使用BuffereImage、JFrame和JPanel,但我在让按钮与从文件读取的BuffereImage交互时遇到了问题。这是我的密码: import java.awt.*; import java.awt.Graphics; import java.awt.event.*; import javax.swing.*; import java.io.*; import javax.imageio.ImageIO

我正在尝试用Java开发一个图像编辑器,目前使用BuffereImage、JFrame和JPanel,但我在让按钮与从文件读取的BuffereImage交互时遇到了问题。这是我的密码:

   import java.awt.*;
   import java.awt.Graphics;

   import java.awt.event.*;
   import javax.swing.*;
   import java.io.*;
   import javax.imageio.ImageIO;
   import java.awt.image.BufferedImage;
   import java.io.IOException;



/**
This class just holds the main
*/
    public class ImageEditorDeluxe
   {
       public static void main(String[] args)
      {
         ProgramWindow p = new ProgramWindow();
         p.setBounds(100, 100, 500, 500);
         p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         p.setVisible(true);
        //  p.pack();
      }
   }

/**
This is where all of the JPanels will come together
*/
    class ProgramWindow extends JFrame  
   {
       ProgramWindow()
      {
         ImagePanel ip = new ImagePanel();
         ChooseFile cf = new ChooseFile();
         ButtonPanel bp = new ButtonPanel(ip.getImg());

         add(ip, BorderLayout.CENTER);
         add(cf, BorderLayout.SOUTH);
         add(bp, BorderLayout.WEST);
      }
   }

/**
This is where the image will be displayed
*/
    class ImagePanel extends JPanel
   {
      BufferedImage img;

       ImagePanel()
      {
         setBackground(Color.BLUE);  //to test
         final JButton button = new JButton ("Display picture");
         add(button);       

         ActionListener action = 
             new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
               {
                  if (e.getSource()==button)
                  {
                     try
                     {
                        img = ImageIO.read(ChooseFile.getFile());
                     }
                         catch(IOException f)
                        {
                           f.printStackTrace();
                        }

                     repaint();

                  }
               }

            };

         button.addActionListener(action);
      }

       public void paintComponent(Graphics g)
      {
         super.paintComponent(g);
         if (img != null)
            g.drawImage(img, 0, 0, this);
      }

       public void setImage(BufferedImage i)
      {
         img = i;
         repaint();
      }
        public BufferedImage getImg()
        {
            return img;
        }
   }

/**
This is where the JFileChooser will exist
*/

    class ChooseFile extends JPanel
   {
      static File file;
      JButton bOpen, bDisplay;
      BufferedImage img;


       ChooseFile()
      {
         setBackground(Color.GREEN); //to test
         bOpen = new JButton("Open File");
         add(bOpen);
      //    bDisplay = new JButton("Display File");
      //    add(bDisplay);
         final JFileChooser chooser = new JFileChooser();


         ActionListener action = 
             new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
               {
                //open file
                  if (e.getSource()==bOpen)
                  {
                     chooser.showOpenDialog(null);
                     file = chooser.getSelectedFile();
                  }
                //display file
               /*       if (e.getSource()== bDisplay)
                  {
                     try
                     {
                        img = ImageIO.read(file);
                     }
                         catch(IOException f)
                        {
                           f.printStackTrace();
                        }

                  }*/
               }

            };

         bOpen.addActionListener(action);
      //        bDisplay.addActionListener(action);
      }

    //returns String name of file
       static File getFile() throws IOException
      {
         return file;
      }
   }

    class ButtonPanel extends JPanel
   {
        JButton makeBlue;
        public static BufferedImage img;
        public static int width, height;
        //BufferedImage img;
       ButtonPanel(BufferedImage x)
      {

            img = x;
            int width, height;
         setBackground(Color.RED);
         makeBlue = new JButton("Make Blue");
         add(makeBlue);
         ActionListener action = 
             new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
               {
                        int width, height;
                  if (e.getSource()== makeBlue)
                  {
                            //img = x;
                         width = img.getWidth();
                             height = img.getHeight();
                             System.out.println(width + " " + height);
                     repaint();

                  }
               }

            };

         makeBlue.addActionListener(action);
      }
   }
错误在ButtonPanel类的某个地方,但我不确定它是什么。当我按下makeBlue按钮时,当前出现的错误如下:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at ButtonPanel$1.actionPerformed(ImageEditorDeluxe.java:185)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:708)
    at java.awt.EventQueue$4.run(EventQueue.java:706)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

任何帮助都将不胜感激。谢谢。

堆栈跟踪非常清晰:

线程“AWT-EventQueue-0”java.lang.NullPointerException中出现异常

按钮上显示$1.actionPerformed(ImageEditorDeluxe.java:185)

这可以归结为以下代码行:

width = img.getWidth();
class ButtonPanel extends JPanel
{
    JButton makeBlue;
    public static BufferedImage img;
    public static int width, height;
    //BufferedImage img;
    ButtonPanel(BufferedImage x)
    {
    
        img = x;
        int width, height;
        setBackground(Color.RED);
        makeBlue = new JButton("Make Blue");
        add(makeBlue);
        ActionListener action = 
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    int width, height;
                    if (e.getSource()== makeBlue)
                    {
                        //img = x;
                        width = img.getWidth();
                        height = img.getHeight();
                        System.out.println(width + " " + height);
                        repaint();

                    }
                }

            };

        makeBlue.addActionListener(action);
    }
}
在这段较大的代码中:

width = img.getWidth();
class ButtonPanel extends JPanel
{
    JButton makeBlue;
    public static BufferedImage img;
    public static int width, height;
    //BufferedImage img;
    ButtonPanel(BufferedImage x)
    {
    
        img = x;
        int width, height;
        setBackground(Color.RED);
        makeBlue = new JButton("Make Blue");
        add(makeBlue);
        ActionListener action = 
            new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    int width, height;
                    if (e.getSource()== makeBlue)
                    {
                        //img = x;
                        width = img.getWidth();
                        height = img.getHeight();
                        System.out.println(width + " " + height);
                        repaint();

                    }
                }

            };

        makeBlue.addActionListener(action);
    }
}

看起来
img
null
。使用调试器找出原因并进行相应的修复。

ImageEditorDeluxe.java:185,该行有什么功能?您应该知道如何查看异常堆栈跟踪并识别失败的行。然后,从那里追溯并找出指针为空的原因是一件相对简单的事情。我对Java非常熟悉,这是一个雄心勃勃的项目。我不知道如何查看异常堆栈跟踪或它是什么。然后做一些研究。了解如何调试的基本知识是您需要立即学习的基本技能。无论何时开始一种新的语言或环境,您都应该首先找到合适的文档并将其添加到书签中,并了解在出现错误时如何读取“调用堆栈”。Java实际上使后一个问题变得非常简单,因为它默认生成堆栈跟踪。您应该能够在没有任何帮助的情况下查看它并理解它的基本原理,但是如果您确实有特定的问题,请返回并提出特定的问题。我将代码更改为:
JButton makeBlue;缓冲图像img;ButtonPanel(BuffereImage x){img=x;int-width,height;..
但是现在我得到了这个错误:
错误:局部变量宽度是从内部类中访问的;需要声明为final-width=img.getWidth()
@masonc15进行必要的调试,以找出为什么您的
img
null
。我对调试并不熟悉,也不知道该问题的明确解决方法。我知道这与作用域有关。@masonc15现在您有很好的理由学习了。