gpt4 book ai didi

java - JTable 构造函数可以接受数组以外的其他数据结构吗?

转载 作者:行者123 更新时间:2023-12-01 23:17:35 24 4
gpt4 key购买 nike

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);

我想知道我们是否可以使用链表来代替。

最佳答案

这是一个示例,其中 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

另请参阅this answer我在哪里使用了 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;
}
}

关于java - JTable 构造函数可以接受数组以外的其他数据结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20986248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com