Rayden Black
Rayden Black

Reputation: 135

having NullPointerException in JTable using MouseListener event

I am new to java and I am trying to build a simple project that connects to database then display it on JTable with MouseClick event. When i click in the row to transfer its content to JTextFields but it returns NullPointerException in line 225. Here's the full code of my project:

package Dbase;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;

@SuppressWarnings("serial")
public class MainForm extends JFrame {
Connection con;
Statement stmt;
ResultSet rs;
PreparedStatement pstmt;
@SuppressWarnings("rawtypes")
Vector columnNames = new Vector();
@SuppressWarnings("rawtypes")
Vector data = new Vector();
//JTable table;

private JPanel gui;

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

/**
 * Create the frame.
 */
public MainForm() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    setLookAndFeel();
    setSize(800,500);
    gui = new JPanel();
    gui.setLayout(new BorderLayout(5, 5));
    setContentPane(gui);

    DBConnect();
    initComponents();
    tbData();
}

public void DBConnect(){
    try{
        String host = "jdbc:mysql://localhost:3306/birthdb";
        String uName = "admin";
        String uPass = "46m1n";
        // connection to mysql database
        con = DriverManager.getConnection(host, uName, uPass);
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String sql = "SELECT * FROM childinfo";
        rs = stmt.executeQuery(sql);



    }
    catch(SQLException er){
        JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
    }
}

private void initComponents(){
    //child's information
    JLabel lblfirstName = new JLabel("FirstName", JLabel.RIGHT);
    JLabel lbllastName = new JLabel("LastName", JLabel.RIGHT);
    JLabel lblmiddleName = new JLabel("MiddleName", JLabel.RIGHT);
    JLabel lblbirthDate = new JLabel("BirthDate",JLabel.RIGHT);
    JLabel lblgender = new JLabel("Gender",JLabel.RIGHT);
    JLabel lblbirthType = new JLabel("BirthType", JLabel.RIGHT);
    JLabel lblmultiBirth = new JLabel("If Multiple Birth, Child Was", JLabel.RIGHT);
    JLabel lblbirthOrder = new JLabel("BirthOrder", JLabel.RIGHT);
    JLabel lblbirthWeight = new JLabel("BirthWeight",JLabel.RIGHT);
    JLabel lblregistry = new JLabel("Registry",JLabel.RIGHT);

    JTextField txtfirstName = new JTextField();
    JTextField txtlastName = new JTextField();
    JTextField txtmiddleName = new JTextField();
    JTextField txtbirthDate = new JTextField();
    JTextField txtgender = new JTextField();
    JTextField txtbirthType = new JTextField();
    JTextField txtmultiBirth = new JTextField();
    JTextField txtbirthOrder = new JTextField();
    JTextField txtbirthWeight = new JTextField();
    JTextField txtregistry = new JTextField();

    JButton newData = new JButton("New");
    JButton updateData = new JButton("Update");
    JButton deleteData = new JButton("Delete");
    JButton printData = new JButton("Print");

    JMenuBar menuBar;
    JMenu menu;
    JMenuItem menuItem;

    menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    //trial menu
    menu = new JMenu("File");
    menu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(menu);

    //trial menu item
    menuItem = new JMenuItem("Quit");
    menuItem.setMnemonic(KeyEvent.VK_Q);
    menu.add(menuItem);

    //trial row panel
    JPanel row = new JPanel(new GridLayout(6,4,5,10));
    row.add(lblregistry);
    txtregistry.setEditable(false);
    row.add(txtregistry);
    row.add(lblfirstName);
    txtfirstName.setEditable(false);
    row.add(txtfirstName);
    row.add(lbllastName);
    txtlastName.setEditable(false);
    row.add(txtlastName);
    row.add(lblmiddleName);
    txtmiddleName.setEditable(false);
    row.add(txtmiddleName);
    row.add(lblgender);
    txtgender.setEditable(false);
    row.add(txtgender);
    row.add(lblbirthDate);
    txtbirthDate.setEditable(false);
    row.add(txtbirthDate);
    row.add(lblbirthType);
    txtbirthType.setEditable(false);
    row.add(txtbirthType);
    row.add(lblmultiBirth);
    txtmultiBirth.setEditable(false);
    row.add(txtmultiBirth);
    row.add(lblbirthOrder);
    txtbirthOrder.setEditable(false);
    row.add(txtbirthOrder);
    row.add(lblbirthWeight);
    txtbirthWeight.setEditable(false);
    row.add(txtbirthWeight);


    gui.add(row, BorderLayout.NORTH);

    JPanel buttonPanel = new JPanel(new BorderLayout(3,3));
    gui.add(buttonPanel,BorderLayout.WEST);
    JPanel btn = new JPanel(new GridLayout(6,1,5,5));
    btn.add(newData);
    btn.add(updateData);
    btn.add(deleteData);
    btn.add(printData);
    buttonPanel.add(btn);



}
@SuppressWarnings("unchecked")
private void tbData(){
    try{
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String sql = "SELECT ChildID, FirstName, LastName, MiddleName FROM childinfo";
        rs = stmt.executeQuery(sql);

        ResultSetMetaData md = rs.getMetaData();
        int columns = md.getColumnCount();

        for(int i = 1; i <= columns; ++i){
            columnNames.add(md.getColumnName(i));
        }
        while(rs.next()){
            @SuppressWarnings("rawtypes")
            Vector row = new Vector(columns);
            for(int i = 1; i<= columns; i++){
                row.addElement(rs.getObject(i));
            }
            data.addElement(row);
        }
        rs.close();
        stmt.close();
    }
    catch(SQLException e){
        JOptionPane.showMessageDialog(MainForm.this, e.getMessage());
    }
    DefaultTableModel model = new DefaultTableModel(data,columnNames);
    JTable table = new JTable(model){
        @SuppressWarnings({ "rawtypes" })
        public Class getColumnClass(int column){
            for(int row = 0; row < getRowCount(); row++){
                Object o = getValueAt(row,column);
                if(o != null){
                    return o.getClass();
                }
            }
            return Object.class;
        }
    };
    table.setRowSelectionAllowed(true);
    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent evt) {
            int row = table.getSelectedRow();
            try{        
                String dataClick = (table.getModel().getValueAt(row, 0).toString());
                stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                String sql = "SELECT * FROM childinfo WHERE ChildID='"+dataClick+"'";
                rs = stmt.executeQuery(sql);

                if(rs.next()){
                    txtregistry.setText(Integer.toString(rs.getInt("ChildID"))); *this is where i get the error*
                    txtfirstName.setText(rs.getString("FirstName"));
                    txtlastName.setText(rs.getString("LastName"));
                    txtmiddleName.setText(rs.getString("MiddleName"));
                    txtgender.setText(rs.getString("Gender"));
                    txtbirthDate.setText(rs.getString("BirthDate"));
                    txtbirthType.setText(rs.getString("BirthType"));
                    txtmultiBirth.setText(rs.getString("IfMultiBirth"));
                    txtbirthOrder.setText(Integer.toString(rs.getInt("BirthOrder")));
                    txtbirthWeight.setText(Integer.toString(rs.getInt("BirthWeight")));
                }

            }
            catch(SQLException er){
                JOptionPane.showMessageDialog(MainForm.this, er.getMessage());
            }
        }
    });
    JScrollPane scrollPane = new JScrollPane(table);
    gui.add(scrollPane, BorderLayout.CENTER);
}
private void setLookAndFeel(){
    try{
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    }
    catch(Exception ee){

    }
}

JTextField txtfirstName;
JTextField txtlastName;
JTextField txtmiddleName;
JTextField txtbirthDate;
JTextField txtgender;

JTextField txtbirthType;
JTextField txtmultiBirth;
JTextField txtbirthOrder;
JTextField txtbirthWeight;
JTextField txtregistry;
JTable table;

Kindly help me to fix the problem.

Upvotes: 0

Views: 490

Answers (1)

Reimeus
Reimeus

Reputation: 159874

You're shadowing all the variable names for the components used in your class. E.g. Replace

JTextField txtfirstName = new JTextField();

with

txtfirstName = new JTextField();

Upvotes: 3

Related Questions