[英]Populate JTable Using List
How will I populate a JTable with values from a List with an Object Type. 如何使用具有对象类型的List中的值填充JTable。 My Code looks like this :
我的代码看起来像这样:
String[] columnNames = {"CLASS CODE",
"TIME",
"DAY",
"ROOM",
"PROFESSOR"};
List<org.mine.ScheduleAttr> schedule = getStudSched(studNo);
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
model.setColumnIdentifiers(columnNames);
I already have the columns, the list would come from the schedule variable ? 我已经有了列,列表会来自schedule变量吗? How can I put that to my table considering these columns ?
考虑到这些列,我怎么能把它放到我的桌子上?
Take a look at DefaultTableModel . 看看DefaultTableModel 。 You could iterate over your List and create the Object array for each row.
您可以迭代List并为每行创建Object数组。
for (ScheduleAttr s : schedule) {
Object[] o = new Object[5];
o[0] = s.getX();
o[1] = s.getY();
o[2] = s.getZ();
o[3] = s.getA();
o[4] = s.getB();
model.addRow(o);
}
You could use something similar to (just changing columns
and values
): 您可以使用类似的东西(只更改
columns
和values
):
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class TestJFrame extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
TestJFrame testJFrame = new TestJFrame();
List<String> columns = new ArrayList<String>();
List<String[]> values = new ArrayList<String[]>();
columns.add("col1");
columns.add("col2");
columns.add("col3");
for (int i = 0; i < 100; i++) {
values.add(new String[] {"val"+i+" col1","val"+i+" col2","val"+i+" col3"});
}
TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][] {}), columns.toArray());
JTable table = new JTable(tableModel);
testJFrame.setLayout(new BorderLayout());
testJFrame.add(new JScrollPane(table), BorderLayout.CENTER);
testJFrame.add(table.getTableHeader(), BorderLayout.NORTH);
testJFrame.setVisible(true);
testJFrame.setSize(200,200);
}
}
The columns
doesn't need to look like columns.toArray()
because you already have an array of objects, so is just use it. 这些
columns
不需要看起来像columns.toArray()
因为你已经有了一个对象数组,所以只是使用它。 At the end in order to use your columns the instruction looks like: TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][] {}), columnNames);
最后,为了使用您的列,指令如下所示:
TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][] {}), columnNames);
try this 试试这个
first make a iterator 首先做一个迭代器
Iterator itr = StringList.iterator();
while(itr.hasNext()) {
Object element = itr.next();
int y=0;
for (y=0; y <=16 ; y++){
table_4.setValueAt(element, y, 0);
table_4 is your table name then set the row and column where you want to insert the string table_4是您的表名,然后设置要插入字符串的行和列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.