如何向 JTable (Java) 添加一种类型的侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7454194/
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
How to add a type of listener to a JTable (Java)?
提问by Confiqure
I have a column with plain text in it.
我有一个包含纯文本的列。
If the user double-clicks a row in that column, the column allows itself to be edited for that row (as it should).
如果用户双击该列中的一行,则该列允许针对该行进行编辑(应该如此)。
I need something to detect when that text is done with being edited (when the user hits the enter key, for example). When that happens, I need something to get the row ID of that change (0-based of course).
我需要一些东西来检测该文本何时完成编辑(例如,当用户按下 Enter 键时)。发生这种情况时,我需要一些东西来获取该更改的行 ID(当然是基于 0)。
Any ideas?
有任何想法吗?
Thanks!
谢谢!
回答by Oleg Pavliv
You should add a listener to the TableModel:
您应该向 TableModel 添加一个侦听器:
table.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
// your code goes here;
}
});
TableModelEventcontains row and column number and type of modification.
TableModelEvent包含行列号和修改类型。
回答by Costis Aivalis
I think the easiest way to get the location of the click in terms of row and column would be this:
我认为根据行和列获取点击位置的最简单方法是:
table.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
int column = table.columnAtPoint(e.getPoint());
if (row >= 0 && column >= 0) {
......
}
}
});