如何动态添加列并用Java swing中的数据填充新添加的列 [英] How to dynamically add a column and fill the newly added column with data in java swing

查看:288
本文介绍了如何动态添加列并用Java swing中的数据填充新添加的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先创建了一个Jtable(通过netbeans GUI),它具有单列和6行(空列).接下来,我使用以下命令

I have first created a Jtable(thru netbeans GUI) with single column and 6 rows (empty column). Next I have added a column dynamically using the following command

summaryTableForVAriousSm.getColumnModel().addColumn(new TableColumn());

在运行应用程序时,我可以看到该列是动态创建的.因此,我想使用

While running the application I can see that the column is created dynamically. So I felt like adding data to the newly created column using the command

summaryTableForVAriousSm.setValueAt("1000", 1, 1);

(对于所有其他6行,按列填充类似) 此更改也反映在应用程序的运行中,但是这里的问题是,插入到新创建的列中的数据也被列0中的数据覆盖(如果存在任何数据).为什么一列中的更改反映在另一列中.还有如何使它们分开,以使一列中的更改不会影响另一列中的数据.

(similarly for all other 6 rows filling column wise) This change is also reflected in the running of application, but the problem here is the data inserted in the newly created column is also being overridden in the column 0 (if any data is present). why the changes in one column are being reflected in the other column. Also how can keep them separate, so that changes in one columns doesn't affect data in other column.

推荐答案

将数据设置为第一列的原因是两列都映射到基础模型中的同一列.请参阅TableDoc()的api文档:

The reason the data is set to the first column is that both columns are mapped to the same column in the underlying model. See the api doc for TableColumn():

使用默认的模型索引为0,默认宽度为75,空渲染器和空编辑器

using a default model index of 0, default width of 75, a null renderer and a null editor

(由我嘲笑)

现在,表的setValueAt位于视图坐标中,并在内部转换为模型坐标.对于基本上通过查询其modelIndex的列:

Now the table's setValueAt is in view coordinates, that are internally converted to model coordinates. For columns basically by querying its modelIndex:

// in JTable.setValueAt
int modelColumnIndex = getColumnModel().getColumn(viewColumn).getModelIndex()

假设基础模型是DefaultTableModel

Assuming the underlying model is a DefaultTableModel

((DefaultTableModel) table.getModel()).addColumn(somename);

这篇关于如何动态添加列并用Java swing中的数据填充新添加的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆