首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不使用tablemodel克隆JTable

不使用tablemodel克隆JTable
EN

Stack Overflow用户
提问于 2018-08-18 18:00:25
回答 1查看 135关注 0票数 2

我想创建一个现有JTable对象的副本。不幸的是,该表可能是使用setValueAt方法填充的,而不是使用tablemodel。那么,在不使用表的模型的情况下“克隆”这样的对象的最佳方法是什么?

谢谢你的任何提示!托尔斯腾

EN

回答 1

Stack Overflow用户

发布于 2018-08-23 15:58:16

我深入研究了setValueAt的实现,并注意到它使用了底层的表模型。因此,解决方案是使用共享表模型,并且您仍然可以在两个表中使用setValueAt。

代码语言:javascript
运行
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51907402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档