单击从Jmenu和按钮中选择的项时的java.lang.NullPointerException

时间:2014-05-23 05:18:48

标签: java swing nullpointerexception jbutton jlist

所以这是一个从数据库中提取数据的Jmenu。错误是当按下视图定义按钮时,相应的事件不会被触发。理想情况下,当用户从Jmenu中选择一个项目并按下该按钮时,再次连接数据库以根据从Jmenu中选择的项目从数据库中获取相应的值。但声明

ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'"); 

似乎永远不会执行并抛出错误

datajava.lang.NullPointerException

导致此问题的错误是什么以及如何解决此问题?这是我的代码: -

public class ListModelExample extends JPanel {

  JList list;

  DefaultListModel model;

  public ListModelExample() {
    setLayout(new BorderLayout());
    model = new DefaultListModel();
    list = new JList(model);
    JScrollPane pane = new JScrollPane(list);
    JButton addButton = new JButton("View Definition");

     Connection con;
      ResultSet rs;
      Statement st = null;

    try {  

        File dbFile = new File("executive_db.accdb");
        String path = dbFile.getAbsolutePath();
        con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       st = con.createStatement();


       } 
    catch (Exception e)
    {  
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);  
System.exit(0);  
   }  


 try {  
     model.clear();  
     rs=st.executeQuery("select Metric_Name from Metrics");  
     while (rs.next())
     {  

         model.addElement(rs.getString("Metric_Name"));  
     }  

    } 
 catch (Exception e)
    {  
     System.out.println("Error in fetching data");  
    }
   addButton.addActionListener(new ActionListener() {
      Statement st;

    public void actionPerformed(ActionEvent e) {

          String def = ""; 


          try {  

                 model.clear();  
                 st = null;
                 System.out.println("came here");
                 ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");  
                 System.out.println("came here too");
                 while (rs.next())
                 {  

                     def = rs.getString("Metric_Name");

                     System.out.println(def);
                   //  model.addElement(rs.getString("Metric_Name"));  
                 }  

                } 
             catch (Exception e1)
                {  
                 System.out.println("Error in fetching data"+e1);  
                }
          System.out.println(def);
          JOptionPane.showMessageDialog(null, def, "Error", JOptionPane.ERROR_MESSAGE);
      /*  model.addElement("Element " + counter);
        counter++;*/
      }
    });

    add(pane, BorderLayout.NORTH);
    add(addButton, BorderLayout.WEST);

  }

  public static void main(String s[]) {
    JFrame frame = new JFrame("List of Metrics used");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new ListModelExample());
    frame.setSize(260, 200);
    frame.setVisible(true);
  }
}

这是我在做e1.printStackTrace()时得到的错误; 我的代码中的第94行是

ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'"); 

java.lang.NullPointerException
    at ListModelExample$1.actionPerformed(ListModelExample.java:94)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$400(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)Error in fetching datajava.lang.NullPointerException


    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

4 个答案:

答案 0 :(得分:3)

看看你的代码:

st = null;
ResultSet rs = st.executeQuery(...);

如果没有获得NullPointerException,则无法在空引用上调用任何方法。您需要将st变量初始化为非null语句。

答案 1 :(得分:2)

首先将st设置为null,然后尝试执行Query

             st = null;
             System.out.println("came here");
             ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");  

而是调用con.prepareStatement(String sql)来获取st

答案 2 :(得分:2)

                 st = null;
                 System.out.println("came here");
                 ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");  

我注意到上面代码的这一部分,它实际上会导致空指针。

要解决此问题,请将此“st”的声明作为主类的字段或成员变量(ListModelExample)。并在侦听器中删除st = null和'Statement = st'成员变量声明。

    File dbFile = new File("executive_db.accdb");
    String path = dbFile.getAbsolutePath();
    con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   st = con.createStatement();

答案 3 :(得分:0)

只需在 public void actionPerformed(ActionEvent e)方法中添加

st = con.createStatement();

完整代码:

public class ListModelExample extends JPanel {

      JList list;

      DefaultListModel model;
      Connection con;
      public ListModelExample() {
        setLayout(new BorderLayout());
        model = new DefaultListModel();
        list = new JList(model);
        JScrollPane pane = new JScrollPane(list);
        JButton addButton = new JButton("View Definition");


          ResultSet rs;
          Statement st = null;

        try {  

            File dbFile = new File("executive_db.accdb");
            String path = dbFile.getAbsolutePath();
            con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           st = con.createStatement();


           } 
        catch (Exception e)
        {  
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);  
    System.exit(0);  
       }  


     try {  
         model.clear();  
         rs=st.executeQuery("select Metric_Name from Metrics");  
         while (rs.next())
         {  

             model.addElement(rs.getString("Metric_Name"));  
         }  

        } 
     catch (Exception e)
        {  
         System.out.println("Error in fetching data");  
        }
       addButton.addActionListener(new ActionListener() {
          Statement st;

        public void actionPerformed(ActionEvent e) {

              String def = ""; 
              st = null;

              try {  

                     model.clear();  

                     st = con.createStatement();
                     System.out.println("came here");
                     ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");  
                     System.out.println("came here too");
                     while (rs.next())
                     {  

                         def = rs.getString("Metric_Name");

                         System.out.println(def);
                       //  model.addElement(rs.getString("Metric_Name"));  
                     }  

                    } 
                 catch (Exception e1)
                    {  
                     System.out.println("Error in fetching data"+e1);  
                    }
              System.out.println(def);
              JOptionPane.showMessageDialog(null, def, "Error", JOptionPane.ERROR_MESSAGE);
          /*  model.addElement("Element " + counter);
            counter++;*/
          }
        });

        add(pane, BorderLayout.NORTH);
        add(addButton, BorderLayout.WEST);

      }

      public static void main(String s[]) {
        JFrame frame = new JFrame("List of Metrics used");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new ListModelExample());
        frame.setSize(260, 200);
        frame.setVisible(true);
      }
    }