我正在尝试使用循环向表中添加行。我的代码如下:
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Test {
public void testCase(){
DefaultTableModel listTableModel;
listTableModel = new DefaultTableModel();
for(int i = 1; i < 25 ; i++){
String rowString = "Quiz #" + i;
listTableModel.addRow(new Object[]{rowString, "ICON", "ICON"});
}
JTable listTable;
listTable = new JTable(listTableModel);
listTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
listTable.setCellEditor(null);
listTable.setBounds(37, 143, 397, 183);
//listTable.getColumnModel().getColumn(0).setPreferredWidth(300);
JFrame frame = new JFrame();
frame.add(listTable);
frame.setVisible(true);
frame.pack();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test tester = new Test();
tester.testCase();
}
}
使用硬编码表,此方法返回功能表。硬编码看起来像:
listTableModel = new DefaultTableModel( new Object[][] {{1,1,1}{2,2,2},{3,3,3}}, new String[] {"Col1, Col2, Col3});
return listTableModel;
这段代码没有给我任何结果。我将它插入一个面板,它没有显示在面板中
我不确定为什么这不起作用,因为我所做的所有研究都指出我这样做...... 感谢任何帮助,谢谢!
答案 0 :(得分:3)
在这里,你应该使用Call by value并初始化表的行和列对象,试试这段代码
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Test {
private static final Object[][] rowData = {};
private static final Object[] columnNames = {"Column 1", "Column 2","Column 3"};
public void testCase() {
DefaultTableModel listTableModel;
listTableModel = new DefaultTableModel(rowData, columnNames);
for (int i = 1; i < 25; i++) {
String rowString = "Quiz #" + i;
listTableModel.addRow(new Object[]{rowString, "ICON", "ICON"});
}
//listTableModel = new DefaultTableModel(50, 50);
JTable listTable;
listTable = new JTable(listTableModel);
listTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
listTable.setCellEditor(null);
listTable.setBounds(37, 143, 397, 183);
JFrame frame = new JFrame();
frame.add(listTable);
frame.setVisible(true);
frame.pack();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Test tester = new Test();
tester.testCase();
}
}