使用来自 ArrayList <HashMap>的数据加载 JTable



我试图让JTable从存储在ArrayList中的数据加载与HashMaps。代码看起来像

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中。

我已经尝试了一些选项,但没有按预期工作。

提前谢谢。

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

但是,一旦

您找到一种机制来确定列顺序作为HashMap而不是无排序,使用此数据结构创建TableModel将相当简单。

Swing 表教程包含有关创建TableModel实例的部分

只需扩展 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)

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

最新更新