0

//Tell if this needs more info

I want to add the integers inside a cell in a column. Here's my code:

// it's in a mouse listener, eveything works fine, but what I want to do is to add
// the values (for ex. 300,400,500) 

    public void mouseClicked(MouseEvent e) {

    if(e.getClickCount() == 2) {
        JTable tbl = (JTable)e.getSource();
        int selectedRow = tbl.getSelectedRow();
        int tbl1_col = 0; // table 1's column to get the data from
        int tbl2_col = 0; // table 2's column to put the data to

   ((DefaultTableModel)tbl2.getModel()).addRow(new Object[] {null,null,null,null}); 
   //to automatically add a new row

    while(tbl1_col<tbl1.getColumnCount()) {
            tbl2.setValueAt(tbl1.getValueAt(selectedRow,tbl1_col),tbl2_row,tbl2_col);
            // Setting the value to be put on to table 2 from table 1

            System.out.println(tbl2.getValueAt(tbl2_row,3));

            tbl1_col++;
            tbl2_col++;

                if(rcol==tbl1.getColumnCount()){
                            tbl2_row++;
                }

                label.setText(String.valueOf(totalAmount));
     }
}

There's a System.out.println over there to see what values are inside and the outputs were:

null null null 300

My code to add the values:

totalAmount = totalAmount + (int) tbl2.getValueAt(tbl2_row,3));

The error I get:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3736846
  • 5
  • 1
  • 6
  • 2
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson Dec 24 '14 at 06:05
  • *"//Tell if this needs more info"* Um... Do you have a question, and if so, what is it? – Andrew Thompson Dec 24 '14 at 06:06
  • `totalAmount = totalAmount + (int) tbl2.getValueAt(tbl2_row,3));` I guess this line is throwing the error since you have null values in the table. try `totalAmount = totalAmount + (int) (tbl2.getValueAt(tbl2_row,3) == null ? 0 : tbl2.getValueAt(tbl2_row,3));` – eatSleepCode Dec 24 '14 at 07:18
  • can you post the complete code? – eatSleepCode Dec 24 '14 at 07:19
  • @eatSleepCode I dunno if this is legit right. I replaced the "((DefaultTableModel)tbl2.getModel()).addRow(new Object[] {null,null,null,null})" replacing null with 0's and it works – user3736846 Dec 24 '14 at 09:58

0 Answers0