java 通过 AbstractTableModel 获取选定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/856888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:05:21  来源:igfitidea点击:

getting selected row through AbstractTableModel

javaswingjtable

提问by Hamza Yerlikaya

Is it possible to get the selected row index from my table model?

是否可以从我的表模型中获取选定的行索引?

My object already knows about the table model. Instead of passing a reference to the table it self can i get the selected index using the model?

我的对象已经知道表模型。我可以使用模型获取选定的索引,而不是传递对表的引用吗?

回答by willcodejavaforfood

Like MrWiggles said you can get it from the ListSelectionModel which you is accessible from the table itself. However there are convenience methods in JTable to get the selected rows as well. If your table is sortable etc you will also need to go through the convertRowIndexToModel method :)

就像 MrWiggles 所说的,你可以从 ListSelectionModel 中获取它,你可以从表本身访问它。然而,在 JTable 中也有一些方便的方法来获取选定的行。如果您的表是可排序的等,您还需要通过 convertRowIndexToModel 方法:)

From the JTable JavaDoc:

来自 JTable JavaDoc:

   int[] selection = table.getSelectedRows();
   for (int i = 0; i < selection.length; i++) {
     selection[i] = table.convertRowIndexToModel(selection[i]);
   }
   // selection is now in terms of the underlying TableModel

回答by tddmonkey

The TableModel only concerns itself with the data, the ListSelectionModel concerns itself with what is currently selected, so, no you can't get the selected row from the TableModel.

TableModel 只关心自己的数据,ListSelectionModel 关心自己当前选择的内容,因此,不,您无法从 TableModel 中获取选定的行。

回答by Peter ?tibrany

If you let your model class implement ListSelectionModel as well as TableModel, you will be able to get selection from one model... but you cannot extend two abstract model classes :-( (It also isn't very good idea anyway as your class will have too many responsibilities).

如果你让你的模型类实现 ListSelectionModel 和 TableModel,你将能够从一个模型中获得选择......但是你不能扩展两个抽象模型类 :-( (这也不是一个好主意,因为你的类将承担太多的责任)。

回答by John Zhang

You can get the index from the bound Table and then you can use it to manipulate the table model. For example, if I want to delete a Row in my table model:

您可以从绑定的表中获取索引,然后可以使用它来操作表模型。例如,如果我想删除表模型中的一行:

myTableModel.removeValueAt(myTable.getSelectedRow());