Java JTable 获取所选行的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29345792/
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
Java JTable getting the data of the selected row
提问by ZeroCool
Are there any methodsthat are used to get the data of the selected row? I just want to simply click a specific row with data on it and click a button that will print the data in the Console.
是否有任何方法可用于获取所选行的数据?我只想单击带有数据的特定行,然后单击将在控制台中打印数据的按钮。
采纳答案by ManyQuestions
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
You will find these methods in it:
您会在其中找到这些方法:
getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()
Use a mix of these to achieve your result.
使用这些的组合来实现你的结果。
回答by Damilola Fagoyinbo
if you want to get the data in the entire row, you can use this combination below
如果要获取整行的数据,可以使用下面这个组合
tableModel.getDataVector().elementAt(jTable.getSelectedRow());
Where "tableModel" is the model for the table that can be accessed like so
其中“tableModel”是可以像这样访问的表的模型
(DefaultTableModel) jTable.getModel();
this will return the entire row data.
这将返回整个行数据。
I hope this helps somebody
我希望这可以帮助某人
回答by Saminda Peramuna
You can use the following code to get the value of the first column of the selected row of your table.
您可以使用以下代码获取表格中所选行的第一列的值。
int column = 0;
int row = table.getSelectedRow();
String value = table.getModel().getValueAt(row, column).toString();
回答by ParisaN
using from ListSelectionModel
:
使用来自ListSelectionModel
:
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedRow.length; i++) {
for (int j = 0; j < selectedColumns.length; j++) {
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});