java.lang.NullPointerException: 无法调用“javax.swing.table.DefaultTableModel.setRowCount(int)
java.lang.NullPointerException: Cannot invoke "javax.swing.table.DefaultTableModel.setRowCount(int)
我完全是 Java 编程的初学者(实际上是一般编程),我正在制作一个简单的学生数据库 GUI 程序。我正在使用 Swing 的应用程序 Window 来创建我的程序的 GUI 设计。这是我到目前为止所做的代码...
package StudentDatabase;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Toolkit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class studentDatabase {
private JFrame frmStudentDatabase;
private JTextField courseTextField;
private JTextField yearTextField;
private JTextField genderTextField;
private JTextField remarkTextField;
private JTextField clearedTextField;
private JTable table;
private DefaultTableModel model;
Connection conn = null;
Statement stmt;
PreparedStatement pst;
ResultSet rs;
private JLabel totalLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
studentDatabase window = new studentDatabase();
window.frmStudentDatabase.setVisible(true);
} catch (Exception err) {
err.printStackTrace();
}
}
});
}
// user-defined method
private Connection dbConnect() { // Step 1 - Get a connection to SQLite database
try {
// Step 1.1 - load Java's JDBC SQLite Driver
//Class.forName("org.sqlite.jdbc");
// Step 1.2 - get a DB Connection
conn = DriverManager.getConnection("jdbc:sqlite:C:\Users\LENOVO\Desktop\student.db"); // created using DB Browser
// prompt user if connection attempt is successful
JOptionPane.showMessageDialog(null, "Connection Successful.");
return conn;
}
catch (Exception err)
{
JOptionPane.showMessageDialog(null, "Connection unsuccessful. Exception -> "+err);
return null;
}
}
// user-defined method
private void resultSetToTableModel(ResultSet rs)
{
model.setRowCount(0); // reset or clear the table model
int count=0;
try {
while (rs.next()) { // add each record in the ResultSet rs to the JTable
Object[] row = {rs.getString("ID"),rs.getString("Name"),rs.getString("Course"),rs.getString("Year"),
rs.getString("Gender"),rs.getString("Score"),rs.getString("Total"),rs.getString("Grade"),
rs.getString("Remark"),rs.getString("Cleared")};
model.addRow(row);
count++; // increment number of student records copied to the JTable
}
totalLabel = null;
totalLabel.setText("Total Students: "+count);
} catch (Exception err) {
JOptionPane.showMessageDialog(null, "ResultSet Exception -> "+err);
}
}
/**
* Create the application.
*/
public studentDatabase() {
initialize();
conn = dbConnect(); // Step 1: Get a connection to SQLite database
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmStudentDatabase = new JFrame();
frmStudentDatabase.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\Users\LENOVO\Pictures\database-icon-4.jpg"));
frmStudentDatabase.setTitle("Student Database");
frmStudentDatabase.setBounds(100, 100, 520, 370);
frmStudentDatabase.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmStudentDatabase.getContentPane().setLayout(null);
JLabel filters = new JLabel("FILTERS");
filters.setFont(new Font("Tahoma", Font.BOLD, 12));
filters.setBounds(10, 11, 70, 14);
frmStudentDatabase.getContentPane().add(filters);
JLabel course = new JLabel("Course");
course.setBounds(20, 36, 46, 14);
frmStudentDatabase.getContentPane().add(course);
JLabel year = new JLabel("Year");
year.setBounds(20, 61, 46, 14);
frmStudentDatabase.getContentPane().add(year);
JLabel gender = new JLabel("Gender");
gender.setBounds(20, 86, 46, 14);
frmStudentDatabase.getContentPane().add(gender);
JLabel remark = new JLabel("Remark");
remark.setBounds(20, 111, 46, 14);
frmStudentDatabase.getContentPane().add(remark);
JLabel cleared = new JLabel("Cleared");
cleared.setBounds(20, 136, 46, 14);
frmStudentDatabase.getContentPane().add(cleared);
courseTextField = new JTextField();
courseTextField.setBounds(76, 33, 100, 20);
frmStudentDatabase.getContentPane().add(courseTextField);
courseTextField.setColumns(10);
JButton nextButton1 = new JButton(">>");
nextButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String course=courseTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Course='"+course+"'"; // select all columns from the student SQLite
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton1.setBounds(186, 32, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton1);
yearTextField = new JTextField();
yearTextField.setColumns(10);
yearTextField.setBounds(76, 58, 100, 20);
frmStudentDatabase.getContentPane().add(yearTextField);
JButton nextButton2 = new JButton(">>");
nextButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int year = Integer.parseInt(yearTextField.getText());
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Year="+year; // select all columns from the student (SQLite DB) with year
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton2.setBounds(186, 57, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton2);
genderTextField = new JTextField();
genderTextField.setColumns(10);
genderTextField.setBounds(76, 83, 100, 20);
frmStudentDatabase.getContentPane().add(genderTextField);
JButton nextButton3 = new JButton(">>");
nextButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String gender=genderTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Gender='"+gender+"'"; // select all columns from the student (SQLite DB) gender
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton3.setBounds(186, 82, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton3);
remarkTextField = new JTextField();
remarkTextField.setColumns(10);
remarkTextField.setBounds(76, 108, 100, 20);
frmStudentDatabase.getContentPane().add(remarkTextField);
JButton nextButton4 = new JButton(">>");
nextButton4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String remark=remarkTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Remark='"+remark+"'"; // select all columns from the student (SQLite DB) gender
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton4.setBounds(186, 107, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton4);
clearedTextField = new JTextField();
clearedTextField.setColumns(10);
clearedTextField.setBounds(76, 133, 100, 20);
frmStudentDatabase.getContentPane().add(clearedTextField);
JButton nextButton5 = new JButton(">>");
nextButton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String cleared=clearedTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Cleared='"+cleared+"'"; // select all columns from the student (SQLite DB) gender
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton5.setBounds(186, 132, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton5);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// create a Statement through the connection
stmt = conn.createStatement();
// execute the Statement which is to insert the new student record/data
stmt.executeUpdate("INSERT INTO student (ID,Name,Course,Year,Gender,Score,Total,Grade,Remark,Cleared) "
+ "values ('2022-001','Juan Cruz','BSCPE','1','Male',95,96,97,'Fair','TRUE')");
}
catch(Exception err) {
err.printStackTrace();
}
}
});
addButton.setIcon(new ImageIcon("C:\Users\LENOVO\Downloads\Webp.net-resizeimage (6).png"));
addButton.setBounds(245, 32, 90, 23);
frmStudentDatabase.getContentPane().add(addButton);
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id="2022-001";
try {
// create a Statement through the connection
stmt = conn.createStatement();
// execute the Statement which is to delete the existing student record that satisfy the condition id=<specify..
stmt.executeUpdate("DELETE FROM student WHERE ID='"+id+"'");
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
deleteButton.setIcon(new ImageIcon("C:\Users\LENOVO\Downloads\Webp.net-resizeimage (7).png"));
deleteButton.setBounds(245, 57, 90, 23);
frmStudentDatabase.getContentPane().add(deleteButton);
JButton editButton = new JButton("Edit");
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id="2022-001";
try {
// create a Statement through the connection
stmt = conn.createStatement();
// execute the Statement which is to update/edit the 3 data fields/columns Score,Grade & Remark of the existing SQLite DB
stmt.executeUpdate("UPDATE student set Score=99,Grade=99,Remark='Excellent' WHERE ID='"+id+"'");
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
editButton.setIcon(new ImageIcon("C:\Users\LENOVO\Downloads\Webp.net-resizeimage (8).png"));
editButton.setBounds(245, 82, 90, 23);
frmStudentDatabase.getContentPane().add(editButton);
JButton loadButton = new JButton("Load Database to Table");
loadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student"; // select all columns/data fields from the student (SQLite DB)
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
loadButton.setBounds(345, 32, 149, 23);
frmStudentDatabase.getContentPane().add(loadButton);
JButton cayButton = new JButton("Course AND Year");
cayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String course = courseTextField.getText();
int year = Integer.parseInt(yearTextField.getText());
try {
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Course='"+course+"' and Year="+year; // select all columns from course and year
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and the store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
cayButton.setBounds(345, 57, 149, 23);
frmStudentDatabase.getContentPane().add(cayButton);
JButton yorButton = new JButton("Year OR Remark");
yorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int year = Integer.parseInt(yearTextField.getText());
String remark = remarkTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Year="+year+" or Remark="+remark+"'"; // select all columns from year and remark
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
yorButton.setBounds(345, 82, 149, 23);
frmStudentDatabase.getContentPane().add(yorButton);
JButton clearButton = new JButton("Clear Filters");
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
courseTextField.setText("");
yearTextField.setText("");
genderTextField.setText("");
remarkTextField.setText("");
clearedTextField.setText("");
}
});
clearButton.setBounds(345, 107, 149, 23);
frmStudentDatabase.getContentPane().add(clearButton);
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exitButton.setBounds(345, 132, 149, 23);
frmStudentDatabase.getContentPane().add(exitButton);
JLabel totalLabel = new JLabel("Total Students: ");
totalLabel.setBounds(20, 175, 156, 14);
frmStudentDatabase.getContentPane().add(totalLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 200, 484, 120);
frmStudentDatabase.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ID", "Name", "Course", "Year", "Gender", "Score", "Total", "Grade", "Remark", "Cleared"
}
));
}
}
我正在尝试连接到我创建的 SQLite 数据库,但我经常被这个错误阻碍...
java.lang.NullPointerException: Cannot invoke "javax.swing.table.DefaultTableModel.setRowCount(int)" because "this.model" is null
at StudentDatabase.studentDatabase.resultSetToTableModel(studentDatabase.java:80)
at StudentDatabase.studentDatabase.actionPerformed(studentDatabase.java:365)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
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:6616)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3398)
at java.desktop/java.awt.Component.processEvent(Component.java:6381)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4991)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4823)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4823)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:775)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:720)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:714)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:747)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:745)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:744)
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)
我知道它很长,这是我无法追踪错误主要原因的主要原因。我怀疑我无法连接到我的数据库,这就是我出现此错误的原因。你们有人遇到过这个错误吗?
我相信很明显 private DefaultTableModel model;
为 null 且未在您的应用程序中的任何位置初始化?
我完全是 Java 编程的初学者(实际上是一般编程),我正在制作一个简单的学生数据库 GUI 程序。我正在使用 Swing 的应用程序 Window 来创建我的程序的 GUI 设计。这是我到目前为止所做的代码...
package StudentDatabase;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Toolkit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class studentDatabase {
private JFrame frmStudentDatabase;
private JTextField courseTextField;
private JTextField yearTextField;
private JTextField genderTextField;
private JTextField remarkTextField;
private JTextField clearedTextField;
private JTable table;
private DefaultTableModel model;
Connection conn = null;
Statement stmt;
PreparedStatement pst;
ResultSet rs;
private JLabel totalLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
studentDatabase window = new studentDatabase();
window.frmStudentDatabase.setVisible(true);
} catch (Exception err) {
err.printStackTrace();
}
}
});
}
// user-defined method
private Connection dbConnect() { // Step 1 - Get a connection to SQLite database
try {
// Step 1.1 - load Java's JDBC SQLite Driver
//Class.forName("org.sqlite.jdbc");
// Step 1.2 - get a DB Connection
conn = DriverManager.getConnection("jdbc:sqlite:C:\Users\LENOVO\Desktop\student.db"); // created using DB Browser
// prompt user if connection attempt is successful
JOptionPane.showMessageDialog(null, "Connection Successful.");
return conn;
}
catch (Exception err)
{
JOptionPane.showMessageDialog(null, "Connection unsuccessful. Exception -> "+err);
return null;
}
}
// user-defined method
private void resultSetToTableModel(ResultSet rs)
{
model.setRowCount(0); // reset or clear the table model
int count=0;
try {
while (rs.next()) { // add each record in the ResultSet rs to the JTable
Object[] row = {rs.getString("ID"),rs.getString("Name"),rs.getString("Course"),rs.getString("Year"),
rs.getString("Gender"),rs.getString("Score"),rs.getString("Total"),rs.getString("Grade"),
rs.getString("Remark"),rs.getString("Cleared")};
model.addRow(row);
count++; // increment number of student records copied to the JTable
}
totalLabel = null;
totalLabel.setText("Total Students: "+count);
} catch (Exception err) {
JOptionPane.showMessageDialog(null, "ResultSet Exception -> "+err);
}
}
/**
* Create the application.
*/
public studentDatabase() {
initialize();
conn = dbConnect(); // Step 1: Get a connection to SQLite database
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmStudentDatabase = new JFrame();
frmStudentDatabase.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\Users\LENOVO\Pictures\database-icon-4.jpg"));
frmStudentDatabase.setTitle("Student Database");
frmStudentDatabase.setBounds(100, 100, 520, 370);
frmStudentDatabase.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmStudentDatabase.getContentPane().setLayout(null);
JLabel filters = new JLabel("FILTERS");
filters.setFont(new Font("Tahoma", Font.BOLD, 12));
filters.setBounds(10, 11, 70, 14);
frmStudentDatabase.getContentPane().add(filters);
JLabel course = new JLabel("Course");
course.setBounds(20, 36, 46, 14);
frmStudentDatabase.getContentPane().add(course);
JLabel year = new JLabel("Year");
year.setBounds(20, 61, 46, 14);
frmStudentDatabase.getContentPane().add(year);
JLabel gender = new JLabel("Gender");
gender.setBounds(20, 86, 46, 14);
frmStudentDatabase.getContentPane().add(gender);
JLabel remark = new JLabel("Remark");
remark.setBounds(20, 111, 46, 14);
frmStudentDatabase.getContentPane().add(remark);
JLabel cleared = new JLabel("Cleared");
cleared.setBounds(20, 136, 46, 14);
frmStudentDatabase.getContentPane().add(cleared);
courseTextField = new JTextField();
courseTextField.setBounds(76, 33, 100, 20);
frmStudentDatabase.getContentPane().add(courseTextField);
courseTextField.setColumns(10);
JButton nextButton1 = new JButton(">>");
nextButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String course=courseTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Course='"+course+"'"; // select all columns from the student SQLite
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton1.setBounds(186, 32, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton1);
yearTextField = new JTextField();
yearTextField.setColumns(10);
yearTextField.setBounds(76, 58, 100, 20);
frmStudentDatabase.getContentPane().add(yearTextField);
JButton nextButton2 = new JButton(">>");
nextButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int year = Integer.parseInt(yearTextField.getText());
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Year="+year; // select all columns from the student (SQLite DB) with year
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton2.setBounds(186, 57, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton2);
genderTextField = new JTextField();
genderTextField.setColumns(10);
genderTextField.setBounds(76, 83, 100, 20);
frmStudentDatabase.getContentPane().add(genderTextField);
JButton nextButton3 = new JButton(">>");
nextButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String gender=genderTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Gender='"+gender+"'"; // select all columns from the student (SQLite DB) gender
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton3.setBounds(186, 82, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton3);
remarkTextField = new JTextField();
remarkTextField.setColumns(10);
remarkTextField.setBounds(76, 108, 100, 20);
frmStudentDatabase.getContentPane().add(remarkTextField);
JButton nextButton4 = new JButton(">>");
nextButton4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String remark=remarkTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Remark='"+remark+"'"; // select all columns from the student (SQLite DB) gender
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton4.setBounds(186, 107, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton4);
clearedTextField = new JTextField();
clearedTextField.setColumns(10);
clearedTextField.setBounds(76, 133, 100, 20);
frmStudentDatabase.getContentPane().add(clearedTextField);
JButton nextButton5 = new JButton(">>");
nextButton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String cleared=clearedTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Cleared='"+cleared+"'"; // select all columns from the student (SQLite DB) gender
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
nextButton5.setBounds(186, 132, 49, 23);
frmStudentDatabase.getContentPane().add(nextButton5);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// create a Statement through the connection
stmt = conn.createStatement();
// execute the Statement which is to insert the new student record/data
stmt.executeUpdate("INSERT INTO student (ID,Name,Course,Year,Gender,Score,Total,Grade,Remark,Cleared) "
+ "values ('2022-001','Juan Cruz','BSCPE','1','Male',95,96,97,'Fair','TRUE')");
}
catch(Exception err) {
err.printStackTrace();
}
}
});
addButton.setIcon(new ImageIcon("C:\Users\LENOVO\Downloads\Webp.net-resizeimage (6).png"));
addButton.setBounds(245, 32, 90, 23);
frmStudentDatabase.getContentPane().add(addButton);
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id="2022-001";
try {
// create a Statement through the connection
stmt = conn.createStatement();
// execute the Statement which is to delete the existing student record that satisfy the condition id=<specify..
stmt.executeUpdate("DELETE FROM student WHERE ID='"+id+"'");
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
deleteButton.setIcon(new ImageIcon("C:\Users\LENOVO\Downloads\Webp.net-resizeimage (7).png"));
deleteButton.setBounds(245, 57, 90, 23);
frmStudentDatabase.getContentPane().add(deleteButton);
JButton editButton = new JButton("Edit");
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id="2022-001";
try {
// create a Statement through the connection
stmt = conn.createStatement();
// execute the Statement which is to update/edit the 3 data fields/columns Score,Grade & Remark of the existing SQLite DB
stmt.executeUpdate("UPDATE student set Score=99,Grade=99,Remark='Excellent' WHERE ID='"+id+"'");
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
editButton.setIcon(new ImageIcon("C:\Users\LENOVO\Downloads\Webp.net-resizeimage (8).png"));
editButton.setBounds(245, 82, 90, 23);
frmStudentDatabase.getContentPane().add(editButton);
JButton loadButton = new JButton("Load Database to Table");
loadButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student"; // select all columns/data fields from the student (SQLite DB)
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
loadButton.setBounds(345, 32, 149, 23);
frmStudentDatabase.getContentPane().add(loadButton);
JButton cayButton = new JButton("Course AND Year");
cayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String course = courseTextField.getText();
int year = Integer.parseInt(yearTextField.getText());
try {
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Course='"+course+"' and Year="+year; // select all columns from course and year
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and the store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
cayButton.setBounds(345, 57, 149, 23);
frmStudentDatabase.getContentPane().add(cayButton);
JButton yorButton = new JButton("Year OR Remark");
yorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int year = Integer.parseInt(yearTextField.getText());
String remark = remarkTextField.getText();
try
{
// Step 2 - Prepare the SQL command
String query = "SELECT * FROM student WHERE Year="+year+" or Remark="+remark+"'"; // select all columns from year and remark
pst = conn.prepareStatement(query);
// Step 3 - execute SQL command or the query and store in ResultSet
rs = pst.executeQuery();
// Step 4 - Convert ResultSet to TableModel
resultSetToTableModel(rs);
}
catch(Exception err)
{
err.printStackTrace();
}
}
});
yorButton.setBounds(345, 82, 149, 23);
frmStudentDatabase.getContentPane().add(yorButton);
JButton clearButton = new JButton("Clear Filters");
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
courseTextField.setText("");
yearTextField.setText("");
genderTextField.setText("");
remarkTextField.setText("");
clearedTextField.setText("");
}
});
clearButton.setBounds(345, 107, 149, 23);
frmStudentDatabase.getContentPane().add(clearButton);
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exitButton.setBounds(345, 132, 149, 23);
frmStudentDatabase.getContentPane().add(exitButton);
JLabel totalLabel = new JLabel("Total Students: ");
totalLabel.setBounds(20, 175, 156, 14);
frmStudentDatabase.getContentPane().add(totalLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 200, 484, 120);
frmStudentDatabase.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ID", "Name", "Course", "Year", "Gender", "Score", "Total", "Grade", "Remark", "Cleared"
}
));
}
}
我正在尝试连接到我创建的 SQLite 数据库,但我经常被这个错误阻碍...
java.lang.NullPointerException: Cannot invoke "javax.swing.table.DefaultTableModel.setRowCount(int)" because "this.model" is null
at StudentDatabase.studentDatabase.resultSetToTableModel(studentDatabase.java:80)
at StudentDatabase.studentDatabase.actionPerformed(studentDatabase.java:365)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
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:6616)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3398)
at java.desktop/java.awt.Component.processEvent(Component.java:6381)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4991)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4823)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4823)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:775)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:720)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:714)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:747)
at java.desktop/java.awt.EventQueue.run(EventQueue.java:745)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:744)
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)
我知道它很长,这是我无法追踪错误主要原因的主要原因。我怀疑我无法连接到我的数据库,这就是我出现此错误的原因。你们有人遇到过这个错误吗?
我相信很明显 private DefaultTableModel model;
为 null 且未在您的应用程序中的任何位置初始化?