public JTable(Object rowData[][], Object columnNames[])
Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3"},
{ "Row2-Column1", "Row2-Column2", "Row2-Column3"} };
Object columnNames[] = { "Column One", "Column Two", "Column Three"};
JTable table = new JTable(rowData, columnNames);
我想知道我们是否可以使用链接列表。
答案 0 :(得分:2)
以下是使用List<List<String>>
代替Object[][]
的示例。我使用了一种方法来创建DefaultTableModel
并将模型设置为JTable
public DefaultTableModel createModel(List<List<String>> list, String[] columnNames) {
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (List<String> row : list) {
model.addRow(row.toArray());
}
return model;
}
请参阅DefaultTableModel javadoc
另请参阅我使用Stack
完整的跑步计划:
import java.awt.BorderLayout;
import java.util.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TestTable {
private String[] colNames = { "Col 1", "Col2", "Col3", "Col4", "Col5" };
private DefaultTableModel model;
private JTable table;
private MyStack myStack = new MyStack();
private List<List<String>> list;
public TestTable() {
list = myStack.getList();
model = createModel(list, colNames);
table = new JTable(model);
JFrame frame = new JFrame();
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public DefaultTableModel createModel(List<List<String>> list, String[] columnNames) {
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (List<String> row : list) {
model.addRow(row.toArray());
}
return model;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TestTable();
}
});
}
}
class MyStack {
public List<List<String>> list = new ArrayList<List<String>>();
public MyStack() {
int k = 1;
for (int i = 0; i < 20; i++) {
List<String> innerList= new ArrayList<String>();
for (int j = 0; j < 5; j++) {
innerList.add(String.valueOf( i * k * (j + 1)));
}
k++;
list.add(innerList);
}
}
public List<List<String>> getList() {
return list;
}
}
答案 1 :(得分:1)
根据Java Docs,它也可以接受向量:http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
另外请注意,您可以将linkedList转换为像yourLinkedList.toArray()
这样的单维数组,然后使用单个循环将其复制到二维数组(如果您愿意,可以将其复制到嵌套循环中)。