在JTable中按正确顺序添加行。

3

我正在编写一段代码,从一个数组列表中收集数组数据,将其添加到 JTable 中。但是,该代码总是将数据从底部向上添加,因此如果有两行数据,则将它们添加到最后两行而不是前两行。以下是相关代码:

public class RegistrationView extends GUIDesign implements ActionListener {

//variable declarations here. 

public RegistrationView (GTPort gport){

    super("Student Report", 3);

    gtPort = gport;

    setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
    setPreferredSize(new Dimension(500,800));

    header = new JPanel();
    header.setSize(getWidth(), 30);
    body = new JPanel();
    body.setLayout(new BoxLayout(body,BoxLayout.Y_AXIS));

    header.setBackground(color);
    title.setFont(new Font("Helvetica", 1,20));
    header.add(title);

    data = new Object[15][4];

    model = new DefaultTableModel(data, columns);

    table = new JTable(model);


    body.add(table.getTableHeader()); 
    body.add(table);


    backButton.addActionListener(this);
    buttonPanel.add(backButton);

    buttonPanel.add(backButton);
    add(header);
    add(body);
    add(buttonPanel);

}

public void refresh()
{
           //this is the data to be added. it is an arraylist of object arrays. 
    ArrayList<Object[]> selectedData = gtPort.selectedData;

           //i use this code to erase all the data in the table, if there is any. this                   //method may be called later, so the data must be erased. 
    model.setRowCount(0);
    table = new JTable(model);
    model.setRowCount(35);

    //adding the rows to the model, which is then added to the table. 

    for (Object[] objects: selectedData)
    {
        model.addRow(objects);


    }

    table = new JTable(model);



}

//谢谢。
3个回答

10
model.addRow(objects); 改为 model.insertRow(0, objects);

好的,那有点帮助。现在它将屏幕的上半部分填充起来,而不是下半部分,但仍然以相反的顺序添加,所以faculty#9出现在第一个位置,#1出现在最后一个位置。 - sparkonhdfs

1

在表格底部添加行,因为如果使用addRow(..)方法,DefaultTableModel将在末尾添加行,如javadoc中所述。使用insertRow(..)方法在特定位置插入行。但要注意ArrayOutOfBoundException.

如javadoc中所述,

 public void insertRow(int row, Object[] rowData)

在模型的行中插入一行。除非指定了rowData,否则新行将包含空值。将生成添加行的通知。

 public void addRow(Object[] rowData)

在模型末尾添加一行。新行将包含空值,除非指定了rowData。将生成添加行的通知。


1

看起来你是在将元素添加到JTable后两次设置行数,以此来添加行。实际上,它应该自动填充而不需要设置行数。如果想要在更改后刷新表格,请尝试使用fireTableDataChanged();,并查看http://docs.oracle.com/javase/tutorial/uiswing/components/table.html以了解如何正确构建布局。


2
如果您正在使用AbstractTableModel,则需要fireTableDataChanged()。但在这种情况下,OP正在使用DefaultTableModel,因此我认为不需要fire方法。如果我错了,请纠正我。 - Amarnath
1
希望你不会建议从模型外部解雇XX;-)通知其监听器是模型本身的独有责任。 - kleopatra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接