【问题标题】:Load JTable with data from ArrayList<HashMap>使用 ArrayList<HashMap> 中的数据加载 JTable
【发布时间】:2012-05-21 17:29:58
【问题描述】:

我正在尝试让 JTable 从存储在带有 HashMaps 的 ArrayList 中的数据中加载。代码看起来像

private ArrayList<HashMap> menuLijst;
private JPanel tablePanel;
//some init
tablePanel = new JPanel();

那么,这是一些随机数据,只是为了确保它有效。

this.menuList = new ArrayList();
// hashmap
HashMap hm1 = new HashMap();
HashMap hm2 = new HashMap();
hm1.put("question", "Contact");
hm1.put("query", "select contact from tim");
hm1.put("message", "contact");
hm2.put("question", "Sales");
hm2.put("query", "select sales from tim");
hm2.put("message", "sales");
menuList.add(hm1);
menuList.add(hm2);    

这就是我的 HashMap 的样子,这有点多余,因为 JTabel 不依赖于预定义的大小数据。

总的来说,我的问题是,如何将 ArrayLists 中的数据与 HashMaps 放在 JTable 中。

我尝试了一些选项,但没有达到应有的效果。

提前致谢。

【问题讨论】:

  • 试图使用 Dacwe 的评论,但同时他删除了它。

标签: java swing arraylist hashmap jpanel


【解决方案1】:

jtable 使用 javabeans 的概念,hashmap 键/值对没有实现为 javabeans 属性。我会使用对类或使用键/值属性定义您自己的对类

【讨论】:

    【解决方案2】:

    您要么创建自己的TableModel 实现(或从一个可用类扩展),要么必须使用其他数据结构(请参阅DefaultTableModel 上的可用构造函数)。

    但是,只要您找到一种将列顺序确定为HashMap 的机制,即没有排序,使用此数据结构创建您的TableModel 将相当简单。

    Swing table tutorial 包含有关创建 TableModel 实例的部分

    【讨论】:

      【解决方案3】:

      只需扩展AbstractTableModel并实现以下方法:

      • getColumnCount
      • getRowCount
      • getValueAt
      • 获取列名

      选择列的出现顺序(例如查询然后消息),并使用

      HashMap map = menuLijst.get(row);
      if (col==0)
           return map.get("query");
      else if (col==1)
           return map.get("message");
      

      实现getValueAt(int row, int col)

      【讨论】:

      • 感谢您的帮助,但我采取了另一种方式。不过还是谢谢
      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 2015-08-13
      • 2013-12-18
      • 1970-01-01
      • 2017-11-20
      • 2013-05-08
      相关资源
      最近更新 更多