Exception in thread “AWT-EventQueue-0“ java.lang.NullPointerException

昨天刚考完试,没想到考的刚好是我考前做的一道题,也刚好那时还遗留了一个错误,结果我照着我做过的做完之后,就剩下那个报错了,搞了大概40分钟之后,还是没有做出来,最后,在我们班学委的帮助下,总算是解决了,希望能对大家有帮助,报错如下:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "javax.swing.JComboBox.getSelectedItem()" because "this.bookType" is null
    at View.ShowFrame.AddBook(ShowFrame.java:184)
    at View.ShowFrame$2.actionPerformed(ShowFrame.java:128)
    at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967)
    at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308)
    at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
    at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
    at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6614)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
    at java.desktop/java.awt.Component.processEvent(Component.java:6379)
    at java.desktop/java.awt.Container.processEvent(Container.java:2263)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4990)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4919)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4548)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4489)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2769)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)


接下来呈上我敲的代码:

package Model;

public class Books {
    private int bookId;
    private String bookName;
    private String bookAuthor;
    private String bookPublish;
    private double bookPrice;
    private String bookType;
    public int getBookId() {
        return bookId;
    }
    public void setBookId(int bookId) {
        this.bookId = bookId;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public String getBookAuthor() {
        return bookAuthor;
    }
    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }
    public String getBookPublish() {
        return bookPublish;
    }
    public void setBookPublish(String bookPublish) {
        this.bookPublish = bookPublish;
    }
    public double getBookPrice() {
        return bookPrice;
    }
    public void setBookPrice(double bookPrice) {
        this.bookPrice = bookPrice;
    }
    public String getBookType() {
        return bookType;
    }
    public void setBookType(String bookType) {
        this.bookType = bookType;
    }
    
}

package Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BUtil {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/library_db?useUnicode=true&characterEncoding=UTF-8";
    private static final String USER = "root";
    private static final String PWD = "666918";

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException var1) {
            var1.printStackTrace();
        }

    }

    public static Connection getConnection() throws Exception {
        return DriverManager.getConnection(URL, USER, PWD);
    }

    public static void close(ResultSet rs, PreparedStatement prep, Connection conn) throws Exception {
        if (rs != null) {
            rs.close();
        }

        if (prep != null) {
            prep.close();
        }

        if (conn != null) {
            conn.close();
        }

    }
}
 

package Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import Model.Books;
import Util.BUtil;


public class BaseDao {
    public ArrayList<Books> getBooks() {
        ArrayList<Books> books=new ArrayList<Books>();
        ResultSet rs=null;
        PreparedStatement prep=null;
        Connection conn=null;
        try {
            conn=BUtil.getConnection();
            String sql="select * from tb_book";
            prep=conn.prepareStatement(sql);
            rs=prep.executeQuery();
            while (rs.next()) {
                Books book=new Books();
                book.setBookId(rs.getInt("bookId"));
                book.setBookName(rs.getString("bookName"));
                book.setBookAuthor(rs.getString("bookAuthor"));
                book.setBookPublish(rs.getString("bookPublish"));
                book.setBookPrice(rs.getDouble("bookPrice"));
                book.setBookType(rs.getString("bookType"));
                books.add(book);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                BUtil.close(rs, prep, conn);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return books;
    }
    
    public int addBook(Books books) {
        int result=0;
        PreparedStatement prep=null;
        Connection conn=null;
        try {
            conn=BUtil.getConnection();
            String sql="insert into tb_book(bookName,bookAuthor,bookPublish,bookPrice,bookType) values (?,?,?,?,?)";
            prep=conn.prepareStatement(sql);
            prep.setString(1, books.getBookName());
            prep.setString(2, books.getBookAuthor());
            prep.setString(3, books.getBookPublish());
            prep.setDouble(4, books.getBookPrice());
            prep.setString(5, books.getBookType());
            result=prep.executeUpdate();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                BUtil.close(null, prep, conn);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
        
    }
    
    public int delBook(int bookId) {
        int result=0;
        PreparedStatement prep=null;
        Connection conn=null;
        try {
            conn=BUtil.getConnection();
            String sql="delete from tb_book where bookId=?";
            prep=conn.prepareStatement(sql);
            prep.setInt(1, bookId);
            result=prep.executeUpdate();    
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                BUtil.close(null, prep, conn);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;    
    }
}
 

package View;

import java.awt.BorderLayout;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import Dao.BaseDao;
import Model.Books;

import javax.swing.JButton;
import javax.swing.DefaultComboBoxModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ShowFrame extends JFrame {
    public DefaultTableModel dtm;
    private JPanel contentPane;
    private JTextField bookName;
    private JTextField bookAuthor;
    private JTextField bookPublish;
    private JTextField bookPrice;
    private JComboBox bookType;
    private JTable table;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ShowFrame frame = new ShowFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ShowFrame() {
        setTitle("\u56FE\u4E66\u4FE1\u606F\u7BA1\u7406\u7CFB\u7EDF");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 621, 313);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        JLabel lblNewLabel = new JLabel("\u56FE\u4E66\u540D\u79F0\uFF1A");
        lblNewLabel.setBounds(23, 10, 89, 22);
        contentPane.add(lblNewLabel);
        
        JLabel lblNewLabel_1 = new JLabel("\u4F5C\u8005\uFF1A");
        lblNewLabel_1.setBounds(23, 40, 89, 22);
        contentPane.add(lblNewLabel_1);
        
        JLabel lblNewLabel_2 = new JLabel("\u51FA\u7248\u793E\uFF1A");
        lblNewLabel_2.setBounds(23, 70, 89, 22);
        contentPane.add(lblNewLabel_2);
        
        JLabel lblNewLabel_3 = new JLabel("\u4EF7\u683C\uFF1A");
        lblNewLabel_3.setBounds(23, 102, 89, 22);
        contentPane.add(lblNewLabel_3);
        
        JLabel lblNewLabel_4 = new JLabel("\u56FE\u4E66\u7C7B\u578B\uFF1A");
        lblNewLabel_4.setBounds(23, 138, 89, 22);
        contentPane.add(lblNewLabel_4);
        
        bookName = new JTextField();
        bookName.setBounds(122, 11, 190, 22);
        contentPane.add(bookName);
        bookName.setColumns(10);
        
        bookAuthor = new JTextField();
        bookAuthor.setBounds(122, 41, 190, 22);
        contentPane.add(bookAuthor);
        bookAuthor.setColumns(10);
        
        bookPublish = new JTextField();
        bookPublish.setBounds(122, 71, 190, 22);
        contentPane.add(bookPublish);
        bookPublish.setColumns(10);
        
        bookPrice = new JTextField();
        bookPrice.setBounds(122, 103, 190, 22);
        contentPane.add(bookPrice);
        bookPrice.setColumns(10);
        
        JComboBox bookType = new JComboBox();
        bookType.setModel(new DefaultComboBoxModel(new String[] {"\u5C0F\u8BF4", "\u7384\u5E7B", "\u6587\u5B66", "\u5386\u53F2", "\u7ECF\u6D4E"}));
        bookType.setBounds(122, 138, 190, 22);
        contentPane.add(bookType);
        
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(322, 10, 285, 180);
        contentPane.add(scrollPane);
        
        table = new JTable();
        table.setModel(new DefaultTableModel(
            new Object[][] {
            },
            new String[] {
                "\u7F16\u53F7", "\u540D\u79F0", "\u4F5C\u8005", "\u51FA\u7248\u793E", "\u4EF7\u683C", "\u7C7B\u578B"
            }
        ));
        scrollPane.setViewportView(table);
        
        JButton btnNewButton = new JButton("\u6DFB\u52A0");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddBook(e);
            }
        });
        btnNewButton.setBounds(48, 209, 97, 23);
        contentPane.add(btnNewButton);
        
        JButton btnNewButton_1 = new JButton("\u6E05\u7A7A");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Clear();
            }
        });
        btnNewButton_1.setBounds(192, 209, 97, 23);
        contentPane.add(btnNewButton_1);
        
        JButton btnNewButton_2 = new JButton("\u5220\u9664");
        btnNewButton_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DelBook(e);
            }
        });
        btnNewButton_2.setBounds(480, 209, 97, 23);
        contentPane.add(btnNewButton_2);
        dtm=(DefaultTableModel)table.getModel();
        search();
    }
    
    protected void DelBook(ActionEvent e) {
        // TODO Auto-generated method stub
        int num=JOptionPane.showConfirmDialog(null, "确定删除吗");
        if (num==0) {
            int bookId=(int)(dtm.getValueAt(this.table.getSelectedRow(), 0));
            BaseDao bd=new BaseDao();
            int result=bd.delBook(bookId);
            if (result>0) {
                JOptionPane.showMessageDialog(null, "删除成功");
                search();
            }
        }
                
    }

    protected void Clear() {
        // TODO Auto-generated method stub
        this.bookName.setText("");
        this.bookAuthor.setText("");
        this.bookPublish.setText(""); 
        this.bookPrice.setText("");
    }

    protected void AddBook(ActionEvent e) {
        // TODO Auto-generated method stub
        String bookName=this.bookName.getText();
        String bookAuthor=this.bookAuthor.getText();
        String bookPublish=this.bookPublish.getText();
        double bookPrice=Double.parseDouble(this.bookPrice.getText());
        String bookType=this.bookType.getSelectedItem().toString();
        
        Books books=new Books();
        books.setBookName(bookName);
        books.setBookAuthor(bookAuthor);
        books.setBookPublish(bookPublish);
        books.setBookPrice(bookPrice);
        books.setBookType(bookType);
        
        BaseDao bd=new BaseDao();
        int result=bd.addBook(books);
        if (result>0) {
            JOptionPane.showMessageDialog(null, "添加图书信息成功!");
        } else {
            JOptionPane.showMessageDialog(null, "填写信息不完整,请认真检查!");
        }
    }

    public void search() {
        dtm.setRowCount(0);
        BaseDao bd=new BaseDao();
        ArrayList<Books> books=bd.getBooks();
        for (Books book : books) {
            Vector v=new Vector();
            v.add(book.getBookId());
            v.add(book.getBookName());
            v.add(book.getBookAuthor());
            v.add(book.getBookPublish());
            v.add(book.getBookPrice());
            v.add(book.getBookType());
            dtm.addRow(v);
        }
    }
}
 

最后把里的JComboBox删掉之后,就信息添加成功了,究其原因,可能是前面已经定义了属性,后面实例化没有赋值,所以就报了空指针异常。

 

 

 

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
引用\[1\]:根据引用内容中的描述,问题中出现的异常是"Exception in thread AWT-EventQueue-0 java.lang.OutOfMemoryError Java heap space"。这个异常通常是由于Java堆内存不足导致的。引用\[3\]中提到,类似的异常也可能是由于加载了过多的软件或者资源导致的。解决这个问题的方式可以尝试增加Java堆内存的大小,可以通过修改Java虚拟机的启动参数来实现。具体的方法是在启动脚本或者命令行中添加"-Xmx"参数,后面跟上所需的堆内存大小,例如"-Xmx2g"表示设置堆内存为2GB。另外,也可以尝试关闭一些不必要的软件或者资源,以释放内存。 #### 引用[.reference_title] - *1* [matlab Exception in thread AWT-EventQueue-0 java.lang.OutOfMemoryError Java heap space](https://blog.csdn.net/qq_41263383/article/details/116449971)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Exception in threadAWT-EventQueue-0“ java.lang.NoClassDefFoundError问题解决](https://blog.csdn.net/qq_40432886/article/details/122235590)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Matlab 2015b 报错 Exception in threadAWT-EventQueue-0“ java.lang.OutOfMemoryError: Java heap](https://blog.csdn.net/baigeyunxue/article/details/121084620)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值