嗨,我正在研究一个项目,我需要使用JTable。我将AbstractTableModel分类,然后将数据放入表中。这工作正常。我在AbstractTableModel中创建了一个新的JTable对象。接下来,我将其设为AutoScrollPane。当我将AutoScrollPane添加到GUI时,表格显示但没有任何数据。我将提供我认为必要的短代码片段,因为我的代码现在有点混乱。
//JPanel tableToShow = new JPanel();
TablePane table = new TablePane(gp.txt);
table.addData();
JTable scrollTable = new JTable(table);
scrollTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
scrollTable.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(scrollTable);
//tableToShow.add(scrollPane);
//text.setFont(new Font("Courier", Font.BOLD, 20));
//text.setPreferredSize(new Dimension(1200,150));
setLayout(new BorderLayout(10,10));
add(jplRadio, BorderLayout.WEST);
add(plotPanel, BorderLayout.EAST);
add(label, BorderLayout.NORTH);
add(scrollPane, BorderLayout.SOUTH);
和
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class TablePane extends AbstractTableModel {
public String[] ColumnNames = {"Date", "Level", "Duration", "Weight"};
public String[][] data = null;
private TextImporter txt = null;
public TablePane(TextImporter txt) {
this.txt = txt;
}
public void addData() {
ArrayList<?> currentList = null;
data = new String[4][txt.getSession().size()];
for(int i = 0; i < ColumnNames.length; i++) {
if(i == 0) {
currentList = txt.getSession();
} else if(i == 1) {
currentList = txt.getAmplitude();
} else if(i==2) {
currentList = txt.getDuration();
} else if(i==3) {
currentList = txt.getLegPressure();
}
for(int j = 0; j < txt.getSession().size(); j++) {
data[i][j] = (String) currentList.get(j);
}
}
//System.out.print(data);
}
// public void displayTable() {
//
// }
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return ColumnNames.length;
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
}
如果需要,我可以提供更多代码