简体   繁体   English

Jtable 获取选定行总是返回 -1

[英]Jtable get selected row always returns -1

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.我在 Eclipse 中使用 WindowBuilder 创建了一个 jTable,目前正在尝试使用 .getSelectedRow() 函数获取所选行的编号,但它始终返回 -1(未选择行),即使我有选择了一些东西。

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)我可以通过单击添加来创建新行(并通过在之前添加按钮旁边的文本字段中输入名称来命名它们)

在此处输入图片说明

在此处输入图片说明

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()});
    }

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.为什么你所得到的理由-1getSelectedRow()即使你似乎已经“添加了一行,”是的,因为Frontend对象,你在呼唤checkActiveItem()上是完全不同的Frontend比你所看到的一个对象。

The issue is here, inside of your Timer s run() :问题就在这里,在你的Timerrun()

Frontend f = new Frontend();

You create a new Frontend object for each timer iteration.您为每个计时器迭代创建一个新的Frontend对象。 And you call checkActiveItem() on exactly this object, not on the frontend you are seeing and pressing buttons on.并且您正是在这个对象上调用checkActiveItem() ,而不是在您看到并按下按钮的前端上。 Hence, the incorrect output.因此,不正确的输出。

As a solution, don't create new Frontend s, instead, call checkActiveItem() on your original frontend object, which you made visible.作为一种解决方案,不要创建新的Frontend ,而是在您使其可见的原始前端对象上调用checkActiveItem()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM