Java JTable,如何更改单元格数据(写入文本)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13114139/
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-10-31 11:32:32  来源:igfitidea点击:

Java JTable, how to change cell data (write text in)?

javaswingjtablelistenertablemodel

提问by thecodefather

Am looking to change a cell's data in a jtable. How can I do this? When I execute the following code I get errors.

我想在 jtable 中更改单元格的数据。我怎样才能做到这一点?当我执行以下代码时,出现错误。

JFrame f= new JFrame();
final JTable table= new JTable(10,5);

TableModelListener tl= new TableModelListener(){
  public void tableChanged(TableModelEvent e){

    table.setValueAt("hello world",2,2);
  }
};

table.getModel().addTableModelListener(tl);
f.add(table);
f.pack();
f.setVisible(true);

I have also tried this below but it still doesn't work. What gives?

我也在下面尝试过这个,但它仍然不起作用。是什么赋予了?

table.getModel().setValueAt("hello world",2,2);

回答by Reimeus

Calling table.setValueAt()within a TableModelListenercauses the tableChanged()method to be called followed by the setValueAt()method being called again and so on ad infinitum, resulting in a StackOverflowError.

调用table.setValueAt()TableModelListener导致tableChanged()被称为方法,接着是setValueAt()一次所谓的对方法的循环往复,导致StackOverflowError

One solution is to use a CellEditorListenerinstead. See this example.

一种解决方案是使用 aCellEditorListener代替。请参阅此示例

回答by Syed Muhammad Mubashir

You can use Rob Camick's example that help me alot, in addition you can get old and new value also by using this class. Example!

您可以使用 Rob Camick 的示例对我有很大帮助,此外您还可以通过使用此类获得新旧价值。 例子

Also look at the end of Blog to see my post to Add Addiional Code to the Form Load Event To Handle Last Change Occur To Your Table.

另请查看博客的末尾以查看我的帖子,将附加代码添加到表单加载事件以处理表中发生的最后更改。

 MouseEvent me = new MouseEvent(tblDetailInfo, 0, 0, 0, 100, 100, 1, false);
for(MouseListener ml: tblDetailInfo.getMouseListeners()){
ml.mouseClicked(me); }