这是我的TableModel,我已经扩展了AbstractTableModel
class CustomTableModel extends AbstractTableModel
{
String[] columnNames = {"Name","Contact","eMail","Address","City","Pin","State","Type","ID"};
Vector<String[]> data = new Vector<String[]>();
CustomTableModel()
{
try
{
//Using JDBC connection//
while(rs.next())
{
String[] s=new String[9];
s[0]=rs.getString(1);
//System.out.println(s[0]);
s[1]=rs.getString(2);
s[2]=rs.getString(3);
s[3]=rs.getString(4);
s[4]=rs.getString(5);
s[5]=rs.getString(6);
s[6]=rs.getString(7);
s[7]=rs.getString(8);
s[8]=rs.getString(9);
data.add(s);
}
}
catch(Exception e)
{
System.out.println("the exception is :"+e.toString());
}
}
public int getColumnCount() {
int columnCount = columnNames.length;
return columnCount;
}
public int getRowCount() {
int rowCount = data.size();
return rowCount;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex)[columnIndex];
}
public String getColumnName(int column) {
return columnNames[column];
}
public void removeRow(int r)
{
for(int i=0;i<data.size();i++)
{
String[] s = (String[])data.get(i);
if(s[0]==getValueAt(r,0))
{
try
{
//using JDBC connections to delete the data from DB//
//also removing the value from data and also updating the view//
data.remove(data.get(i));
fireTableRowsDeleted(r, r);
}
catch (Exception e)
{
System.out.println(e.toString());
}
break;
}
}
}
//I am using the following code to update the view but it doesnot work//
public void addRow(String[] a)
{
data.add(a);
fireTableRowsInserted(data.size() - 1, data.size() - 1);
}
}我有一个扩展CustomTableModel的表类。
class table extends CustomTableModel
{
final JButton editButton = new JButton("Edit");
final JButton deleteButton = new JButton("Delete");
final JTable mytable = new JTable(new CustomTableModel());
.
.
.
} 我有一个add按钮,在它的操作侦听器中,我使用以下代码来传递我想要添加的值。
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);请让我知道我哪里错了。谢谢
发布于 2013-05-22 20:00:45
请让我知道我哪里错了。谢谢
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);1. create a new row
2. create a new `JTable`
3. row is added to a new `JTable`
4. result is that a new `JTable` is never added to visible Swing GUI
5. don't do that, why is a new `JTable` recreated on every `JButton`s event
6. add `String[] a...` to the `CustomTableModel` directly
发布于 2013-05-22 20:07:21
table类毫无意义。它应该是应该设置到JTable中的TableModel。相反,您将JTable声明为这个表类中的一个字段(根据命名约定,它应该是JTable)。结果是,当构造一个新的表对象时,一个JTable被构建在中,而另一个CustomTableModel在里面。因此,要向其中添加行的tableModel不是JTable实际使用的tableModel。
发布于 2013-05-23 00:14:38
您也可以使用myCustomTable.fireTableStructureChanged();
https://stackoverflow.com/questions/16691020
复制相似问题