繁体   English   中英

从向量动态更新JTable <vector<string> &gt;

[英]Dynamically updating a JTable from a vector<vector<string>>

我有一个名为FetchInbox()的函数,该函数获取电子邮件的标头信息(发件人,主题,发送日期),然后将其添加到String Vectors的Vector中。

我希望能够做的是在收到新电子邮件时刷新此表并通过再次运行FetchInbox()来更新表,然后使用它重新填充表。

我知道可以使用TableModel完成此操作,但是我还没有找到使用Vector而不使用Object [] []的示例。 任何帮助,将不胜感激。

DefaultTableModel具有采用Vector而不是Object []的构造函数和方法。

DefaultTableModel的旧版本仅使用Vector,而Object []参数是较新的方法,它们是在泛型Java出现时添加的。

http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

在不提供model的情况下创建表时,它将具有DefaultTableModel作为其默认模型。 该模型具有两个功能:

  1. setDataVector(Vector dataVector, Vector columnIdentifiers) :其中dataVectorVector (表示表的数据行)的Vector而comlumnIdentifiers是包含标识符的Vector 提供Vector时,它将显示您的表格。

  2. addRow(Vector dataRow) :它将如上所述将数据行添加到您的dataVector中。

因此,获取模型并调用以下函数确实非常简单:

 DefaultTableModel model = (DefaultTableModel) table.getModel();
 model.setDataVector(dataVector, comlnIdentifiers);

在您的上下文中, dataVector的类型为vector<vector<string> > 但是依赖Vector并不是一个很好的选择。 如果直接使用Object[]它将更加安全有效。 DefaultTableModel也具有与Object数组相似的功能。

  1. setDataVector(Object[][] dataVector, Object[] columnIdentifiers)
  2. addRow(Object[] rowData)

请查看“教程”页面: 如何使用表,以了解您可以对表及其模型进行的更多操作。

这应该可以,但是@jzd的答案可能是您想要的,但需要注意的是,根据文档,如果Vector的长度与表中所需的列数不匹配,则Vector的列可能会被截断或填充。

import javax.swing.*;
import javax.swing.table.*;
import java.util.*;

class test{
  public static void main(String[] _) {

    // Test data.
    final Vector<Vector<String>> rows = new Vector<Vector<String>>();
    for (int i = 0; i < 4; i++) {
      Vector<String> row = new Vector<String>();
      for (int j = 0; j < 5; j++) {
        row.add(String.format("%s, %s", i, j));
      }
      rows.add(row);
    }

    // With AbstractTableModel, you only need to implement three methods.
    TableModel model = new AbstractTableModel() {
      public int getRowCount() {
        return rows.size();
      }
      public int getColumnCount() {
        return rows.elementAt(0).size();
      }
      public Object getValueAt(int row, int column) {
        return rows.elementAt(row).elementAt(column);
      }
    };

    // Test the TableModel in a JTable.
    JFrame jf = new JFrame("test");
    jf.setSize(512, 384);
    jf.setContentPane(new JScrollPane(new JTable(model)));
    jf.show();

  }
}

看看GlazedLists-它可以为您节省大量时间。 使用它,您可以将JTable动态绑定到对象列表,这样对象中的任何更改都会反映在表中,反之亦然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM