使用clone()
创建您想要克隆的对象的精确副本的方法。要允许克隆你的类必须实现 interface Cloneable
。然后,您必须从您实现的接口覆盖克隆方法。
小例子:
public class TableClass implements Cloneable {
private DefaultTableModel model;
@Override
public Object clone() {
DefaultTableModel cloned = null;
try {
cloned = (DefaultTableModel) super.clone();
}
catch (CloneNotSupportedException ex) {
Logger.getLogger(TableClass.class.getName()).log(Level.SEVERE, null, ex);
}
return cloned;
}
由于clone()
方法返回实例Object
,您必须转换为对象的类型:cloned = (DefaultTableModel) super.clone()
所以这是如何工作的clone()
。现在您可以实现自己的 tableMode。
基本示例:
public class YourTableModel extends AbstractTableModel implements Cloneable {
private static final String[] columnNames = {"URL", "Progress", "Size", "Status"};
private static final Class[] columnClasses = {String.class, String.class, String.class, String.class};
private List<T> yourData;
@Override
public Object clone() {
YourTableModel cloned = null;
try {
cloned = (YourTableModel) super.clone();
}
catch (CloneNotSupportedException ex) {
Logger.getLogger(TableClass.class.getName()).log(Level.SEVERE, null, ex);
}
return cloned;
}
@Override
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return yourData.getName();
case 1:
return yourData.getAge();
case 2:
return yourData.getAddress();
case 3:
return yourData.getSomethingElse();
}
return "";
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return downloadList.size();
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
public Class getClassName(int col) {
return columnClasses[col];
}
}
这样,您还可以实现自己的模型 clone() 方法,然后您可以克隆此对象。但是还有其他方法,例如@vizier 所写
希望能帮助到你!