JTable中的DefaultTableModel空行

时间:2018-05-18 10:31:41

标签: java swing jtable defaulttablemodel

if (!rgb.isEmpty()) {
    rouge.add((Integer) rgb.get(0));
    vert.add((Integer) rgb.get(1));
    bleu.add((Integer) rgb.get(2));
} else {
    Log.e("tag", "ERROR: RGB array is empty");
}

当我运行Jframe时,jTable(TeacherTable)的前4行是空的,所有数据都显示在它下面,没有遗漏。我该如何解决这个问题?

编辑:问题解决了在循环之前添加model.setRowCount(0),但是我还有其他问题,我忘了提及,Last_Name列没有显示任何数据/记录

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Test {
public static void main(String[] args) {
    ArrayList<Teacher> list = new ArrayList<Teacher>();
    Teacher a = new Teacher("1", "Max", "Wonder", "012345", "not so good");
    Teacher b = new Teacher("2", "Brad", "Summer", "98765", "excellent");
    list.add(a);
    list.add(b);
    JTable table = new JTable();
    String headers[] = { "ID", "First_Name", "Last_Name", "Phone", "Experience" };
    DefaultTableModel model = new DefaultTableModel(headers, 0);
    table.setModel(model);

    for (Teacher teacher : list) {
        String id = teacher.getId();
        String first_Name = teacher.getFirst_Name();
        String last_Name = teacher.getLast_Name();
        String phone = teacher.getPhone();
        String experience = teacher.getExperience();

        Object[] data = { id, first_Name, last_Name, phone, experience };
        model.addRow(data);
    }

    System.out.println(table.getValueAt(0, 0));
    System.out.println(table.getValueAt(1, 1));
}

}

老师班喜欢:

public class Teacher {
    private String id, first_Name, last_Name, phone, experience;

    public Teacher(String id, String first_Name, String last_Name, String phone, String experience) {
        this.id = id;
        this.first_Name = first_Name;
        this.last_Name = last_Name;
        this.phone = phone;
        this.experience = experience;
    }
    public String getId() {
        return id;
    }

    public String getFirst_Name() {
        return first_Name;
    }

    public String getLast_Name() {
        return last_Name;
    }

    public String getPhone() {
        return phone;
    }

    public String getExperience() {
        return experience;
    }

}

Printline仅用于检查表格是否为空。

示例输出: 1 布拉德