可能重复:
Is there any way by which I can create a JTable using the data in an ArrayList?
我的程序代码如下:
//A loan Amortization example
public class LoanTable
{
public static void main(String[] args)
{
double p,n,r,a,rb,ia,pa,pno=1;
//creating a double arraylist
List<double[]> l = new ArrayList<double[]>();
p=250000;
n=360;
r=0.416/100;
a=1342.05;
rb=p;
//calculating the amount as interest, amount as principal and remaining balance
for(int i=1; i<=n;i++)
{
ia=(rb*r);
pa=a-ia;
rb=rb-pa;
l.add(new double[] { pno,a,ia,pa,rb });
pno++;
}
for (double[] row : l)
{
System.out.println(Arrays.toString(row));
}
}
}
如何导入行中的值以创建表格?导入值变得很困难。
输出有点像:
[1.0,1342.05,1040.0,302.04999999999999,249697.95]
[2.0,1342.05,1038.7434719999999,303.30652800000007,249394.64347200003]
[3.0,1342.05,1037.48171684352,304.56828315648,249090.07518884353]
[4.0,1342.05,1036.214712785589,305.835287214411,248784.23990162913]
[5.0,1342.05,1034.942437990777,307.1075620092229,248477.13233961992]
[6.0,1342.05,1033.6648705328187,308.3851294671813,248168.74721015274]
[7.0,1342.05,1032.3819883942353,309.6680116057646,247859.07919854697]
[8.0,1342.05,1031.0937694659553,310.9562305340446,247548.12296801293]
[9.0,1342.05,1029.8001915469338,312.2498084530662,247235.87315955988]
[10.0,1342.05,1028.501232343769,313.5487676562309,246922.32439190365]
感谢。
答案 0 :(得分:1)
一种方法是使用List<double[]>
作为AbstractTableModel
中的后备数据。这个表模型有很多good examples可在线获得。
答案 1 :(得分:1)
使用 JTable 时要理解的关键是每个JTable都由 TableModel 内部支持。如果您不熟悉使用表格,我建议将"How to Use Tables"作为开始学习实施的好地方
每个表模型基本上都实现了TableModel接口。对于您的场景,您应该考虑创建自己的表模型,扩展AbstractTableModel类。根据javadoc,
创建具体的TableModel作为AbstractTableModel的子类 您只需要提供以下三种方法的实现:
public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row,int column);
所以你的TableModel的实现将是 minimally 这样的事情[请注意我说的最低限度,因为你还想要覆盖这个类的其他方法,例如getColumnNames (...)]:
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class MyTableModel extends AbstractTableModel {
private List<double[]> dataList;
public MyTableModel(List<double[]> dataList){
this.dataList = dataList;
}
@Override
public int getRowCount() {
return dataList.size();
}
@Override
public int getColumnCount() {
return (dataList.size() > 0) ? dataList.get(0).length : 0;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(rowIndex < dataList.size()){
double[] columns = dataList.get(rowIndex);
if(columns.length > columnIndex){
return columns[columnIndex];
}
}
return null;
}
}