Janaka Pushpakumara
Janaka Pushpakumara

Reputation: 5107

jTable index is wrong

When I select the row in jtable, it always returns -1 as a table row index.

This is how I fill the data to jtable:

private void addResultToRecTable(DefaultTableModel dtm, ArrayList<RecipeModule> al) {

    if (al != null) {
        int rowCount = dtm.getRowCount();
        for (int i = 0; i < rowCount; i++) {
            dtm.removeRow(0);
        }

        for (int i = 0; i < al.size(); i++) {
            String[] recArray = {al.get(i).getRecID(), al.get(i).getRecName(), al.get(i).getRecCategory(), al.get(i).getRecQty(), al.get(i).getRecUnit()};
            dtm.addRow(recArray);

        }
    }

This is how I pass the data to the addResultToRecTable() method:

ArrayList<RecipeModule> al = RecipeController.searchRecipes(txtRepSearchName.getText(), txtRecSearchCate.getText());
addResultToRecTable(recDefaultTableModel, al);

After I filled the data to table. I selected a row in the table and printout selected row index. Then I got this error.

private void tableRecSearchKeyReleased(java.awt.event.KeyEvent evt) {   
    try{
        int selectedRow = tableRecIngredients.getSelectedRow();
        System.out.println(selectedRow);
    }

But I get this error:

java.lang.ArrayIndexOutOfBoundsException: -1

I'm not sure what the problem is. Any advice?

Upvotes: 1

Views: 119

Answers (1)

camickr
camickr

Reputation: 324197

private void tableRecSearchKeyReleased(java.awt.event.KeyEvent evt)

I have no idea what that event is. Maybe the row selection hasn't completed yet.

If you want to know when the row selection has changed then add a ListSelectionListener to the table.

table.getSelectionModel().addListSelectionListener(...);

Read the section from the Swing tutorial on How to Write a List Selection Listener for more information and examples.

    //int rowCount = dtm.getRowCount();
    //for (int i = 0; i < rowCount; i++) {
    //    dtm.removeRow(0);
    //}

To remove all the rows from the table model you can just use:

dtm.setRowCount(0);

Upvotes: 4

Related Questions