JTable 3字段arrayList

时间:2011-03-28 00:08:48

标签: java arraylist jtable

我正在尝试向Jtable添加值,这些值是从arrayList获取的, 你是怎么做的

我尝试制作Object[][] data;并在循环中填充它,但它不起作用,你如何解决这个问题?

String[] columns = {"Field String","Field Double"," Field Double"};
Object[][] data;

Iterator<Node> itr = arrayList.iterator();
while (itr.hasNext()) {
   Node el    = itr.next();
   double a   = el.getval();
   data[i][1] = el.getstring();
   data[i][2] = a;
   data[i][3] = a*4;
   i++;
}


JFrame frame = new JFrame("Title ");
JTable tablE = new JTable(data, columnas);
JPanel panel = new JPanel();

panel.add(table);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);

如何在while循环中填充“数据”?

1 个答案:

答案 0 :(得分:2)

使用DefaultTableModel并使用其addRow(Object [])或addRow(Vector)方法添加数据行。将其设置为JTable的模型。 API和JTable教程可以帮助您入门。

例如,

  ArrayList arrayList = new ArrayList();

  String[] columns = {"Field String","Field Double"," Field Double"};
  DefaultTableModel model = new DefaultTableModel(columns, 0);

  for (Object item : arrayList) {
     Object[] row = new Object[3];
     //... fill in row with info from item

     model.addRow(row);
  }

  JTable table = new JTable(model);

这演示了使用for循环执行此操作,但while循环类似。