java 在 JTable 中获取选定的单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30674612/
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
Get selected cell value in JTable
提问by amirhtk
When I double click the cell of the JTable, I want it to take the value of that cell and write it in the textfield. What should I do? Here is what I have tried so far, but I don't know where to go from here:
当我双击 JTable 的单元格时,我希望它获取该单元格的值并将其写入文本字段。我该怎么办?这是我到目前为止尝试过的,但我不知道从哪里开始:
table_1.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable table = (JTable) me.getSource();
Point p = me.getPoint();
int row = table.rowAtPoint(p);
if (me.getClickCount() == 2) {
textfield.settext(???????????);
}
}
});
i understand how it works:
我明白它是如何工作的:
int row = table.rowAtPoint(p);
int column = table.columnAtPoint(p);
textfield.settext(table_1.getValueAt(row, column));
回答by Adam
Jtable table = (JTable)e.getsource();
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
ObjectType o = (ObjectType)target.getValueAt(row, column) );
Do this. Will get the value in your JTable based on the row and column selected and then casts the returned value to your object type in the table and returns the value at the row, column. This is inside your Listener.
做这个。将根据所选的行和列获取 JTable 中的值,然后将返回的值转换为表中的对象类型,并返回行、列处的值。这是在你的监听器里面。
Shown in similar question Possible Dup?
显示在类似问题可能的重复?
回答by Pawe? G?owacz
Try to write something like this:
尝试写这样的东西:
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 1) {
final JTable jTable= (JTable)e.getSource();
final int row = jTable.getSelectedRow();
final int column = jTable.getSelectedColumn();
final String valueInCell = (String)jTable.getValueAt(row, column);
textfield.setText(valueInCell);
}
});
回答by Andrew Tobilko
You can get the value of the table by using:
您可以使用以下方法获取表的值:
table.getModel().getValueAt(row, col);
where
在哪里
row
- the row whose value is to be queriedcol
- the column whose value is to be queriedtable
- your object name (classjTable
)
row
- 要查询其值的行col
- 要查询其值的列table
- 您的对象名称(类jTable
)
Note:The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.
注意:列是在表视图的显示顺序中指定的,而不是在 TableModel 的列顺序中指定的。这是一个重要的区别,因为当用户重新排列表中的列时,视图中给定索引处的列将发生变化。同时,用户的操作永远不会影响模型的列排序。
In addition, I recommend to read this documentation.
此外,我建议阅读此文档。