我正在尝试创建一个包含多个相应数组的表,这些数组垂直填充信息。如果我的每个数组只有3个数据,下面的代码将完美地运行:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class TableSample {
static String[] itemArray = new String[] {"item1","item2","item3"};
static String[] conditionArray = new String[] {"condition1","condition2","condition3"};
static String[] locationArray = new String[] {"location1","location2","location3"};
public static void main(String args[]) {
JFrame f = new JFrame("JTable Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
Object rows[][] = { { itemArray[0], conditionArray[0], locationArray[0] },
{ itemArray[1], conditionArray[1], locationArray[1] },
{ itemArray[2], conditionArray[2], locationArray[2] } };
Object columns[] = { "Symbol", "Name", "Price" };
JTable table = new JTable(rows, columns);
JScrollPane scrollPane = new JScrollPane(table);
content.add(scrollPane, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
}
}
但是,我的每个阵列都有10,000行,这对于继续填充这些行9,997次非常不切实际。我想创建一个这样的循环:(不起作用,但你知道我想要完成的事情)
for(int i=0;i<itemArray.length;i++)
{
Object rows[][]={
{ itemArray[i], conditionArray[i], locationArray[i] }};
}
答案 0 :(得分:3)
使用DefaultTableModel
方法将数据添加到addRow()
:
DefaultTableModel model = new DefaultTableModel(columns, 0);
for(int i=0;i<itemArray.length;i++)
{
Vector row = new Vector(3);
row.add( itemArray[i] );
row.add( conditionArray[i] );
row.add( locationArray[i] );
model.addRow( row );
}
JTable table = new JTable( model );