Search code examples
javanullpointerexceptionjtabletablemodel

JTable. Printing values of selected row and prompt an error if the selected row is null


I created a JTable with 3 columns and I inserted a value in the first 2 rows. When I select the first row or the second row and click the button "GetData", the data in the selected row will be printed on the console , BUT! if I select a rows with no data in it, there is a NullPointerException on this line of code dataString = dataObject.toString();.

I've inserted if else statement to check the dataString or dataObject if they hold null or " " values

import java.awt.FlowLayout;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class JayTable extends JFrame 
{
    DefaultTableModel model; 
    JTable table;
    String col[] = {"Name","Address","Gender"};

    public static void main(String args[])
    {
        new JayTable().start(); 
    }

    public void start()
    { 
        model = new DefaultTableModel(col,50);
        table=new JTable(model)
        {
            @Override public boolean isCellEditable(int arg0, int arg1) 
            { 
                return false; 
            }
        }; 
        table.getColumnSelectionAllowed();
        JScrollPane pane = new JScrollPane(table); 
        JButton button = new JButton("GetData");
        table.setValueAt("Ritchie Rich",0,0); 
        table.setValueAt("The Mansion",0,1); 
        table.setValueAt("Male",0,2); 
        table.setValueAt("Flintstone", 1, 0);
        table.setValueAt("Rocky Road", 1, 1);
        table.setValueAt("Unknown", 1, 2);

        add(pane);
        add(button);

        button.setEnabled(false);

        ListSelectionModel listSelectionModel = table.getSelectionModel();

        listSelectionModel.addListSelectionListener(new ListSelectionListener() 
        {
                public void valueChanged(ListSelectionEvent e) 
                { 
                    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                    button.setEnabled(!lsm.isSelectionEmpty());
                } 
        });

        button.addActionListener(e ->
        {
            int row = table.getSelectedRow();
            int column;
            Object dataObject = null;
            String dataString = "";

            for(column = 0 ; column < table.getColumnCount(); column++)
            {
                dataObject = table.getValueAt(row, column);
                dataString = dataObject.toString();

                if(dataObject == null || dataObject.equals("") || dataString ==null || dataString.equals("") )
                    System.out.println("No value");
                else
                    System.out.print(dataString+", ");
            }
            System.out.println();
        });

        setSize(500,400);
        setLayout(new FlowLayout()); 
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        pack();
        setVisible(true); 
    }
}

Solution

  • Your null check is too late. Change it to

    dataObject = table.getValueAt(row, column);
    if(dataObject == null || "".equals(dataObject)) {
         System.out.println("No value");
    } else {
          dataString = dataObject.toString();
          if(dataString ==null || "".equals(dataString) )
              System.out.println("No value");
           else
             System.out.print(dataString+", ");
    }