0

I'm a total beginner in Java programming (actually programming in general) and I'm making a simple Student Database GUI program. I am using Swing's Application Window to create the GUI design of my program. Here's the code I've made so far...

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"
            }
        ));
    }
}

I am trying to connect to the the SQLite Database I made but I'm constantly been hindered with this error...

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$10.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$4.run(EventQueue.java:720)
    at java.desktop/java.awt.EventQueue$4.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$5.run(EventQueue.java:747)
    at java.desktop/java.awt.EventQueue$5.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)

I know it's lengthy, that is the main reason why I cannot track the main cause of the error. I'm suspecting that I cannot connect to my database, that's why I had this error. Have anyone of you encountered this error?

kichona
  • 13
  • 2
  • check what you have in result set – GiorgosDev May 18 '22 at 09:40
  • First of all, why would you write 100s of lines of code without doing any testing??? I count 10 instances of `resultSetToTableModel(...)`. So you have 9 buttons that appear to basically to the same code except you change the SQL that is invoked. Start by getting one button to work first and then when that works you know the structure of your code is reasonable and you can repeat for other buttons. It also mean you have less code to post when asking a question. We are not interested in seeing your entire application. We don't have time to read through all the code to spot the error. – camickr May 18 '22 at 14:16
  • Also, don't use setbounds(...). Swing was designed to be used with layout managers. *I'm still having trouble loading my data to my JTable* - because you are not loading the data into the TableModel of your table. `table.setModel(new DefaultTableModel(..` - this is where you create the TableModel of the table. Where do you actually add the data to this model? Nowhere in your code do you invoke `table.getModel()` so you can add the data to this model. Somewhere in your code you must be creating a second TableModel. If you need more help post a proper [mre] using the above suggestions. – camickr May 18 '22 at 14:21
  • Wow, thank you for your suggestions! Actually my program is already resolved before you made the comment. Glad I did what I had to do and am glad you confirmed what I did was right. Thank you! – kichona May 19 '22 at 15:29

1 Answers1

1

I believe it is pretty clear that private DefaultTableModel model; is null and not initialized anywhere in your application?

agulowaty
  • 116
  • 4
  • Thanks so much! The exception is now gone, but I'm still having trouble loading my data to my JTable. I don't know what causes this. – kichona May 18 '22 at 13:51