我想创建一个现有JTable对象的副本。不幸的是,该表可能是使用setValueAt方法填充的,而不是使用tablemodel。那么,在不使用表的模型的情况下“克隆”这样的对象的最佳方法是什么?
谢谢你的任何提示!托尔斯腾
发布于 2018-08-23 15:58:16
我深入研究了setValueAt的实现,并注意到它使用了底层的表模型。因此,解决方案是使用共享表模型,并且您仍然可以在两个表中使用setValueAt。
import javax.swing.*;
import java.awt.*;
public class CloningTablesExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(CloningTablesExample::runApp);
}
static void runApp(){
//create table with default model
JTable original = new JTable(new Object[][]{
{"11", "12"},
{"21", "22"}
},
new String[]{"col1", "col2"}
);
//override value in the model using the original table
original.setValueAt("override from original", 0,0);
//create clone with shared model and (overridden value is visible in both tables)
JTable clone = cloneTable(original);
//override value in the model using the clone table
original.setValueAt("override from clone", 0,1);
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setLayout(new GridLayout(1,2));
window.setSize(600, 200);
window.setVisible(true);
window.getContentPane().add(new JScrollPane(original));
window.getContentPane().add(new JScrollPane(clone));
}
private static JTable cloneTable(JTable original) {
JTable clone = new JTable();
clone.setModel(original.getModel());
return clone;
}
}https://stackoverflow.com/questions/51907402
复制相似问题