Home > Blockchain >  Jtable get selected row always returns -1
Jtable get selected row always returns -1

Time:10-27

I have a problem since yesterday. I'v created a jTable with the WindowBuilder in Eclipse and currently are trying to get the number of the selected row, by using the .getSelectedRow() function, but it is always returning -1 (no row selected), even when I have selected something.

This is my current code for testing the output:

public void checkActiveItem() {
        
        System.out.println(tableBills.getSelectedRow());
        
    }

I try to let it run this way trough a timer and at least that seems working:

Timer time = new Timer();
        time.schedule(new TimerTask() {
            public void run() {
                Frontend f = new Frontend();
                f.checkActiveBill();
                f.checkActiveItem();
            }
        }, 250, 250 );

The table currently has just one entry, but even the first row dosn't get returned on selection. I can create new rows by clicking add (and name them by entering a name in the textfield next to the add button before)

enter image description here

enter image description here

To create a new row I use this code, maybe there is the problem?

public void addBill() {
        //maybe need this value somewhere else to, so let -1 and  1 as it is
        int numbersOfBills = tableBills.getRowCount() - 1;
        Bill newBill = new Bill(txtBillName.getText(), numbersOfBills   1);
        
        DefaultTableModel billModel2 = (DefaultTableModel) tableBills.getModel();
        int billNb = numbersOfBills   1;
        
        billModel2.addRow(new Object[] {newBill.getBillNr(),newBill.getBillName(), newBill.getItemsInBill()});
    }

CodePudding user response:

The reason why you are getting -1 from getSelectedRow() even though you seem to have "added a row" is, because the Frontend object you are calling checkActiveItem() on is a completely different Frontend object than the one you are seeing.

The issue is here, inside of your Timers run():

Frontend f = new Frontend();

You create a new Frontend object for each timer iteration. And you call checkActiveItem() on exactly this object, not on the frontend you are seeing and pressing buttons on. Hence, the incorrect output.

As a solution, don't create new Frontends, instead, call checkActiveItem() on your original frontend object, which you made visible.

  • Related