如何在 JTable 中动态添加行

2022-09-03 03:28:23

我想在JTable中动态添加行,为此我编写了以下代码:

    tblTaskList = new JTable();
    tblTaskList.setShowVerticalLines(false);
    tblTaskList.setCellSelectionEnabled(true);
    tblTaskList.setColumnSelectionAllowed(true);
    tblTaskList.setBorder(new LineBorder(null));
    for (int count = 1; count <= 10; count++) {
        tblTaskList.setModel(new DefaultTableModel(new Object[][] { {
                count, "title1", "start", "stop", "pause", "status" }, },
                new String[] { "status", "Task Title", "Start", "Stop",
                        "Pause", "Status" }));
    }
    tblTaskList.getColumnModel().getColumn(0).setPreferredWidth(31);
    tblTaskList.getColumnModel().getColumn(1).setPreferredWidth(346);
    tblTaskList.getColumnModel().getColumn(2).setPreferredWidth(33);
    tblTaskList.getColumnModel().getColumn(3).setPreferredWidth(31);
    tblTaskList.getColumnModel().getColumn(4).setPreferredWidth(28);

    tblTaskList.setBounds(93, 34, 614, 160);
    frmTaskList.getContentPane().add(tblTaskList);

问题是只添加最后一行,即计数打印第一列中的值10,,,任何人都可以解释如何解决问题吗?


答案 1
 // create object of table and table model
 JTable tbl = new JTable();
 DefaultTableModel dtm = new DefaultTableModel(0, 0);

// add header of the table
String header[] = new String[] { "Prority", "Task Title", "Start",
            "Pause", "Stop", "Statulses" };

// add header in table model     
 dtm.setColumnIdentifiers(header);
   //set model into the table object
       tbl.setModel(dtm);

     // add row dynamically into the table      
for (int count = 1; count <= 30; count++) {
        dtm.addRow(new Object[] { "data", "data", "data",
                "data", "data", "data" });
 }

答案 2

在循环中,您始终将 new 设置为 。相反,您需要创建一个模型实例,然后向其中添加行。使用下一个代码:TableModelJTable

DefaultTableModel model = new DefaultTableModel(new String[] { "status", "Task Title", "Start", "Stop", "Pause", "Status" },0);
tblTaskList.setModel(model);
for (int count = 1; count <= 10; count++) {
     model.addRow(new Object[]{ count, "title1", "start", "stop", "pause", "status" });
}

而不是:

for (int count = 1; count <= 10; count++) {
    tblTaskList.setModel(new DefaultTableModel(new Object[][] { {
            count, "title1", "start", "stop", "pause", "status" }, },
            new String[] { "status", "Task Title", "Start", "Stop",
                    "Pause", "Status" }));
}

推荐