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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:26:48  来源:igfitidea点击:

How to add a table listener to a JTable?

javaswingjtablelistener

提问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
  }
});

TableModelEventcontains row and column number and type of modification.

TableModelEvent包含行号和列号以及修改类型。

TableModelEventis 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 TableModelListenerwith the JTable's model and monitor for changes there

您要做的是TableModelListenerJTable's 模型中注册一个并监视那里的更改

You may also find How to Write a Table Model Listenerof some use

您还可以找到如何编写某些用途的表模型侦听器

The kind of thing you are look for is

你正在寻找的东西是

  • TableModel#getTypeequals TableModelEvent.UPDATE
  • TableModel#getFirstRowand TableModel#getLastRoware typically equals (singularly that a single row was update), this may or may not be relevant, that's up to you to decide
  • TableModel#getColumnis not equal to TableModelEvent.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.TableModelEventfor more details

看看javax.swing.event.TableModelEvent更多细节