java 如何向 JTable 添加表侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28359226/
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 table listener to a JTable?
提问by Seamus O Connor
I am having problems with fixing something in my program. Basically I know how to use action Listeners but there is no option to add one to a JTable
. How is this done?
我在修复程序中的某些内容时遇到问题。基本上我知道如何使用动作监听器,但没有选项可以将一个添加到JTable
. 这是怎么做的?
Basically I want to add an action Listener to my table so that every time a value is changed it will update that field in my data base.
基本上我想在我的表中添加一个动作侦听器,以便每次更改值时它都会更新我的数据库中的该字段。
I.E.
IE
JTable.addActionListener (new ActionListener) {
// text is changed
updateDataBase();
};
回答by Sharp Edge
You should add a listener to the TableModel
:
您应该将侦听器添加到TableModel
:
yourtableObject.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
// your code goes here, whatever you want to do when something changes in the table
}
});
TableModelEvent
contains row and column number and type of modification.
TableModelEvent
包含行号和列号以及修改类型。
TableModelEvent
is used to notify listeners that a table model has changed.
TableModelEvent
用于通知侦听器表模型已更改。
回答by MadProgrammer
Start by taking a look at How to Use Tables
首先看看如何使用表格
What you will want to do is register a TableModelListener
with the JTable
's model and monitor for changes there
您要做的是TableModelListener
在JTable
's 模型中注册一个并监视那里的更改
You may also find How to Write a Table Model Listenerof some use
The kind of thing you are look for is
你正在寻找的东西是
TableModel#getType
equalsTableModelEvent.UPDATE
TableModel#getFirstRow
andTableModel#getLastRow
are typically equals (singularly that a single row was update), this may or may not be relevant, that's up to you to decideTableModel#getColumn
is not equal toTableModelEvent.ALL_COLUMNS
, this signifies that a single cell was updated. Again, this may or may not be important, but if the cell was edited by the user, this will be set
TableModel#getType
等于TableModelEvent.UPDATE
TableModel#getFirstRow
并且TableModel#getLastRow
通常是相等的(特别是单行被更新),这可能相关也可能不相关,这由您决定TableModel#getColumn
不等于TableModelEvent.ALL_COLUMNS
,这表示更新了单个单元格。同样,这可能重要也可能不重要,但如果单元格是由用户编辑的,这将被设置
Take a look at javax.swing.event.TableModelEvent
for more details