Jtable doesn't refresh/update data

前端 未结 2 1737
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 03:07

I have a problem with JTable/JScrollPane. My data table is not refreshing/updating. I am using DefultTableModel and according to the c

2条回答
  •  暖寄归人
    2020-12-20 03:44

    From what I understand from the comments and the question, you have first created a DefaultTableModel by passing the data as arrays in the constructor

    String[][] data = new String[100][4];
    String[] columnNames = new String[]{
         "IP", "PC_NAME", "ttl", "db"};
    DefaultTableModel model = new DefaultTableModel(data,columnNames);
    

    and you try to modify the table afterwards by adjusting those arrays. That will never ever have any effect, as the DefaultTableModel does not use those arrays. This can be seen in the source code of that class

    public DefaultTableModel(Object[][] data, Object[] columnNames) {
        setDataVector(data, columnNames);
    }
    

    which in the end comes down to

    protected static Vector convertToVector(Object[][] anArray) {
        if (anArray == null) {
            return null;
        }
        Vector v = new Vector(anArray.length);
        for (Object[] o : anArray) {
            v.addElement(convertToVector(o));
        }
        return v;
    }
    

    So all the elements of the array are copied into an internal Vector and the array is no longer used.

    Solution: do not update the arrays but update the DefaultTableModel. That class provides all the API you need to add/remove data to/from it.

提交回复
热议问题