Selecting a row in jTable generates error

后端 未结 2 1719
无人及你
无人及你 2021-01-22 10:26

What i\'m trying do here is that when i select a row in my table , after loading data , it should display the selected row\'s value in a text field (selectedRowTF). But as soon

2条回答
  •  逝去的感伤
    2021-01-22 10:53

    If you just load your data, the tbl.getSelectedRow() returns -1.

    After that you try to get the string value of the first column of your invalid row.

    String rowSelected=(tbl.getModel().getValueAt(row, 0).toString());

    => that getValueAt leads to your exception.

    Try the following:

    String rowSelected = "";
    if(row != -1)
    {
        rowSelected = tbl.getModel().getValueAt(row, 0).toString();
    }
    

    EDIT As you said you just want to get the selected value, the position of your code is wrong.

    You are trying to get the value of the selected row at the time you are loading your data. But at that time you don't select a row. I think you need something like that (Value is printed out on a mouse click at the table):

    tbl.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            int row = table.getSelectedRow();
            if (row > -1) {
                String value = (table.getModel().getValueAt(row, 0).toString());
                System.out.println("Value of row " + row + " col 0: '" + value + "'");
                selectedRowTF.setText(value);
            } else {
                System.out.println("Invalid selection");
            }
        }
    });
    

    Or you can react on the selection with a button click:

    private void btClickActionPerformed(java.awt.event.ActionEvent evt) {                                        
        int row = table.getSelectedRow();
        if (row > -1) {
            String value = (table.getModel().getValueAt(row, 0).toString());
            System.out.println("Value of row " + row + " col 0: '" + value + "'");
            selectedRowTF.setText(value);
        } else {
            System.out.println("Invalid selection");
        }
    }   
    

提交回复
热议问题