我有一个带有自定义模型和自定义CellEditor和CellRenderer的JTable,我想在此表中删除和添加数据。
我该怎么做?
我的模特:
public class frandtabmodule extends AbstractTableModel {
Vector list;
public frandtabmodule(Vector frand_list ) {
this.list = frand_list;
}
@Override
public Class getColumnClass(int columnIndex) { return Frand.class; }
@Override
public int getColumnCount() { return 1; }
@Override
public String getColumnName(int columnIndex) { return " "; }
@Override
public int getRowCount() { return (list == null) ? 0 : list.size(); }
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
int i =0 ;
System.out.println(" raw"+rowIndex+" clumn"+columnIndex
+"/n -------------------------------------------"+i++);
return (list == null) ? null : list.get(rowIndex);
}
@Override
public boolean isCellEditable(int columnIndex, int rowIndex) { return true; }
@Override
public void fireTableRowsDeleted(int firstRow, int lastRow) {
this.list.remove(firstRow);
this.fireTableDataChanged();
}
}
我的CellEditor和CellRenderer:
public class renderediter extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
//Clientdef1 clientdef ;
Frand list;
public renderediter(){
//clientdef = new Clientdef1();
}
/*private void updateData(Frand feed, boolean isSelected, JTable table) {
this.feed = feed;
clientdef.setconncted(feed.iscon);
clientdef.name.setText(feed.name);
if (isSelected) {
clientdef.setBackground(table.getSelectionBackground());
}else{
clientdef.setBackground(table.getSelectionForeground());
}
}*/
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
Frand frad = (Frand)value;
System.err.println("-------------------------\n f1 called\n ------------------");
//updateData(feed, true, table);
frad.def.setBackground(table.getSelectionBackground());
return frad.def;
}
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Frand frad = (Frand)value;
// updateData(feed, isSelected, table);
if (isSelected) {
frad.def.setBackground(table.getSelectionBackground());
}
else{
frad.def.setBackground(Color.white);
}
return frad.def;
}
}
创建表格
contact_tab = new javax.swing.JTable();
this.module = new frandtabmodule(client.frands);
contact_tab.setModel(module);
contact_tab.setDefaultEditor(Frand.class, new renderediter());
contact_tab.setDefaultRenderer(Frand.class, new renderediter());
contact_tab.setRowHeight(45);
jsp_contact.add(contact_tab);
jsp_contact.repaint();
jsp_contact.revalidate();
contact_tab.setColumnSelectionAllowed(true);
我尝试过的事情:
添加: client.frands.add(new Frand ());
要删除: client.frands.remove( frand);
如果我从表中选择Cell但我想动态工作,这是有效的。
答案 0 :(得分:1)
请勿覆盖AbstractTableModel
中的fireTableRowsDeleted()
或相关方法。相反,请将您自己的方法实施为addRow()
,removeRow()
等。使用DefaultTableModel
作为指导;检查相关示例here。