0

You want to save what is at the jtable to the database. And just because you can't get the data from the jtable you insert null values and wonder why you get the exception?????

In previous posts you have been told how to get the values from the jtable. Have you looked at the API of JTable?

0

You want to save what is at the jtable to the database. And just because you can't get the data from the jtable you insert null values and wonder why you get the exception?????

In previous posts you have been told how to get the values from the jtable. Have you looked at the API of JTable?

See this is urgent I've already told you that and It'll really take me a deal of a time to get through the JTable then come back to write those code now. All I need write now is to get my save and delete buttons working. I will read the JTable API later. Please help this is quite urgent, you can see here I am putting the best effort I have.

0

In a previous post you used a method that allows you to take the value of a specific cell. It takes 2 arguments (the row and the column). What is wrong with using that.

0

In a previous post you used a method that allows you to take the value of a specific cell. It takes 2 arguments (the row and the column). What is wrong with using that.

It gives me the same exception, that's why I replaced it with this

//A method that locate the exact location of a cellvalue
    // in the JTable
     public Object GetData(JTable visittable, int row_index, int col_index){
    return visittable.getModel().getValueAt(row_index, col_index);
  }
}

Then call it in the delete's action Performed like this

Object obj = GetData(visittable,visittable.getSelectedRow(),visittable.getSelectedColumn());
                    delmthd.delete((String) obj);

But it still gives the same exception:

java.lang.ArrayIndexOutOfBoundsException: -1
0

Have you tried to print the arguments you are using to that method in order to see why you get that error?

You know it is very easy to debug on your own. We are here to help you, but don't just post every error you get and expect others to solve it so you can post the next error and so on and so on. What actions did you took to understand the above error. Have you given any effort apart from posting the error here and waiting.

The above trick of printing the arguments was very easy to think on your own. Students that program for the very first time use that, not someone that wants to be hired as a professional.

Edited by javaAddict: n/a

0

Have you tried to print the arguments you are using to that method in order to see why you get that error?

You know it is very easy to debug on your own. We are here to help you, but don't just post every error you get and expect others to solve it so you can post the next error and so on and so on. What actions did you took to understand the above error. Have you given any effort apart from posting the error here and waiting.

The above trick of printing the arguments was very easy to think on your own. Students that program for the very first time use that, not someone that wants to be hired as a professional.

Thank you very much for all your support!

0

Well, what do you get from printing the arguments? Why do they have those values? What are your conclusions? Asking your self those questions will help you find the answer.

0

Well, what do you get from printing the arguments?

This:
0
1
-1
1
Then the StackTrace Exception
java.lang.ArrayIndexOutOfBoundsException: -1
anyone help on what this might mean I struggle to tackle the problem, but sometiems if you can't you just can't.
Thanks

0

What are those 4 values?

System.err.println(row_index)
System.err.println(col_index)
System.err.println(visittable.getSelectedRow())
System.err.println (visittable.getSelectedColumn())
0

I have been busy, so I could not reply back. Even though your responses haven't been most helpful.

You initially posted 4 values: 0,1,-1,1 without explaining anything. Then again you posted 4 System.out.printlns. Ok I know that this is the command you used , but from where did you call those. Before calling that method you created, after, inside?
Also that method takes 2 arguments and you posted 4 values. The idea is to print the arguments of the method that is giving you the error: getValueAt.
But from the code you wrote that method takes as arguments the row, col which as you said have values 0,1. So you shouldn't be getting ArrayIndexOutOfBoundsException.

So try to post the whole code. Not just some unrelated System.out.printlns. The one that calls the method and prints the values.
Print only the arguments of the method that gives you the exception just before you call it with those arguments.

Because if you use the getSelectedRow/Col that returned -1, of course you would get that exception. But you posted 4 values without saying which of these 2 you used.

0

I have been busy, so I could not reply back. Even though your responses haven't been most helpful.
.

Hey thanks for everyting but i figured it out evnetually.
Here is what I did.

/**This method removes the selected row from the JTable
        * And susequently delete the record from the Ms Access database
        * table
        */
       DelBtn = new JButton("Delete Row");//DelBtn's caption
       DelBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
            //return the index of the selected row
             int row = visittable.getSelectedRow();
            //return the index of the selected column
             int col = visittable.getSelectedColumn();
             //get the value of the current cell
             String idnum = (String) visittable.getModel().getValueAt(row, col);
                try{
                 //Present the user with a choice to authenticate the deletion
                 int selection = JOptionPane.showConfirmDialog(null,
	                    "You are about to delete a record",//Message
                            "DeleteBox",//Title
	                    JOptionPane.YES_NO_OPTION,//Yes or No option
	                    JOptionPane.QUESTION_MESSAGE);//Question mark
                 //if yes is selected
	        if( selection == JOptionPane.YES_OPTION ) {
                    //remove the row from the JTable
                    model.removeRow(visittable.getSelectedRow());
                    //create a new VisitMethods object
                    VisitMethods delmthd  = new VisitMethods();
                    //And call the delete method to subsequently
                    //remove the record from the database table
                   delmthd.delete(idnum);
                   //Inform the model that a set of row have been deleted
                   //between the first row and  the last deleted row +1
                   model.fireTableRowsDeleted(0, visittable.getSelectedRow()+1);
                   refreshwdw();//call the refreshwdw method
                   }
                 //If No is selected
                else{
                     setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//Do nothing
                   }
                }
                //Failure of deletion catches an exception
                catch(Exception ex){
                    ex.printStackTrace();  //Print the StackTrace                 
                }
            }//end of DelBtn's actionPerformed
       });//end of actionListener

I wanted to use this

String idnum = (String) visittable.getModel().getValueAt(row,1)

cause the column IDNum is the second in the table. Do you think that's right?
Thanks for the help!

PS: Solved the save button as well. For that I had to use a parameterized constructor in the Visit class and create instance fields that correspond to the 5 fields of the JTable. Here is what I mean.
1) Parameterized constructor

public Visit(String pn,String id, String fv,String sb, String tp){
        //Setting instance fields to the constructor's parameters
        this.PatientNo = pn;
        this.IDNum = id;
        this.Firstvisit = fv;
        this.Subsequent = sb;
        this.TypeofService = tp;   
   }//End of Parameterised constructor

1) Save method in VisitMethods class

public void save(Visit vInfo) throws SQLException{
        PreparedStatement ps = null;
        Connection cn1 = null;
             
        try{
           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           cn1 = DriverManager.getConnection(url, userid, pass);
           String q ="INSERT INTO VisitTable(PatientNo,IDNum,Firstvisit," +
                      "Subsequent,TypeofService)" +
                      " VALUES(?,?,?,?,?)";           
           
           ps = cn1.prepareStatement(q) ;
           ps.setString(1, vInfo.getPatientNo());
           ps.setString(2, vInfo.getID());
           ps.setString(3, vInfo.getFirst());
           ps.setString(4, vInfo.getSub());
           ps.setString(5, vInfo.getType());
           ps.executeUpdate();
           
            }catch(Exception e){
            e.printStackTrace(); 
            }
        finally{
            if(ps!=null) ps.close();
            if(cn1!=null) cn1.close(); 
            
        }
    }

3) and call them in the save's actionPerformed method like this

/** This method adds new record to the
        *  Ms Access database table from the JTable
        */
       SaveBtn = new JButton("Save Row");
       SaveBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                 
                int curRow = visittable.getSelectedRow();//the current row
                //Assigning instance fields to the 5 cells of the selected row
                PatNum = (String) visittable.getModel().getValueAt(curRow, 0);
                ID = (String) visittable.getModel().getValueAt(curRow, 1);
                Frst = (String) visittable.getModel().getValueAt(curRow, 2);
                Sub = (String) visittable.getModel().getValueAt(curRow, 3);
                Typ = (String) visittable.getModel().getValueAt(curRow, 4);
                
              try{
                    //create a visit object
                   Visit vInfo = new Visit(PatNum,ID,Frst,Sub,Typ);
                   //create a VisitMethods object
                   VisitMethods savmthd = new VisitMethods();
                   //call the save method using the visit object as argument
                   savmthd.save(vInfo);
                   JOptionPane.showMessageDialog(null, "Row save to  database");    
                   //Announce the changes to the table model
                   model.fireTableRowsUpdated(0, visittable.getSelectedRow()+1);
                   refreshwdw();//call the refreshwdw method
                   //Add a new empty row to the JTable
                   model.insertRow(visittable.getRowCount(),
                           new Object[]  {"","","","",""});
           }
          //If attempt fails,  catch a saving attempt failed exception
           catch(Exception saf){
            saf.printStackTrace();//Print the StackTrace
            //Show a message to help the user on how to save the row
            JOptionPane.showMessageDialog(null,"Please fill in all the fields."+
                    "\n"+"Type of Service can't be empty."+"\n"+
                    "Seclect the row and save!");
             }
          }//End of SaveBtn's actionPerformed
       });//end of actionListener

Thanks for the support!

Edited by JBeginer7891: Adding the save button solution

0

Even though it is not a problem, you don't need to call the getSelectedCol, since you don't use it. Also it is not necessary to call so many times the getSelectedRow. You call it once and you get the row. So you can use that.

Also if the user clicks the "Delete" button without selecting a row, it will return -1, as you have noticed from your previous exception. You need to handle that.

int row = visittable.getSelectedRow();
if (row==-1) {
  // no row selected
} else {
   if want to delete the selected row {
     // USING YOUR CODE: 
     String idnum = (String) visittable.getModel().getValueAt(row, 1);

// first delete from database
                    VisitMethods delmthd  = new VisitMethods();
                   delmthd.delete(idnum);

// if the above executes, then you can safely remove it from the table
      model.removeRow(row);                            

model.fireTableRowsDeleted(0,row+1);
                   refreshwdw();
  }
}
0

Even though it is not a problem, you don't need to call the getSelectedCol, since you don't use it. Also it is not necessary to call so many times the getSelectedRow. You call it once and you get the row. So you can use that.

Also if the user clicks the "Delete" button without selecting a row, it will return -1, as you have noticed from your previous exception. You need to handle that.

int row = visittable.getSelectedRow();
if (row==-1) {
  // no row selected
} else {
   if want to delete the selected row {
     // USING YOUR CODE: 
     String idnum = (String) visittable.getModel().getValueAt(row, 1);

// first delete from database
                    VisitMethods delmthd  = new VisitMethods();
                   delmthd.delete(idnum);

// if the above executes, then you can safely remove it from the table
      model.removeRow(row);                            

model.fireTableRowsDeleted(0,row+1);
                   refreshwdw();
  }
}

Thanks very much for your support!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.