how to use hashMap with JTable

前端 未结 6 1891
深忆病人
深忆病人 2021-01-03 02:13

i have a hashMap which i would like its data to be viewed in a JTable how ever i am having trouble getting the hashMap amount of columns and rows and the data to be displaye

6条回答
  •  难免孤独
    2021-01-03 03:09

    You have several options available to you here. I would probably build my own TableModel and convert the HashMap into a List, but that would require that accountID was part of Student and I cannot tell if it is from your post. So probably easier to create a multi dimensional array. To do this you need to examine every object in your HashMap and to do this we would use a 'loop'.

    First create the array to hold your data:

    Object[][] tableData = new Object[students.keySet().size()][numberOfColumns];
    

    Replace numberOfColumns with the number of columns your table has.

    int index = 0;
    for (String key : students.keySet())
    {
        Student student = students.get(key);
        tableData[index][0] = student.getXXX
        tableData[index][1] = student.getYYY
        tableData[index][2] = student.getZZZ
        // and so forth
        index++;
    }
    

    So what we do here is create a loop that will examine every key in the students HashMap and with that key we retrieve the Student object and populate the array with the correct data.

    This is to answer your question, but I would recommend that you take a look at the TableModel interface and build one around your HashMap of Students. More manly :)

提交回复
热议问题