这是我的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());
.
.
.
}
我有一个添加按钮,在其动作监听器中,我使用以下代码传递我想要添加的值。
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);
请告诉我哪里出错了。感谢
答案 0 :(得分:1)
请告诉我哪里出错了。感谢
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);
代码行谈论
创建新行
创建新的JTable
行已添加到新的JTable
结果是永远不会向可见的Swing GUI添加新的JTable
不要这样做,为什么在每个JTable
事件中重新创建新的JButton
直接将String[] a...
添加到CustomTableModel
更快地发布SSCCE,简短,可运行,可编辑
答案 1 :(得分:0)
表类毫无意义。它应该是一个可以设置为JTable的TableModel。相反,您将JTable声明为此表类中的字段(根据Java命名约定,它应该是表 btw)。结果是,在构造新的 table 对象时,JTable在内部中构建,其中另一个CustomTableModel 。因此,要添加行的tableModel不是JTable实际使用的tableModel。
答案 2 :(得分:0)
您还可以使用myCustomTable.fireTableStructureChanged();