我有以下JTable模型:
public class TableModel extends AbstractTableModel{
private String[] columnNames = {"Name", "BornDate", "Salary", "Age", "City"};
private List<Person> personList;
public TableModel(List<Person> personList){
this.personList=personList;
}
public int getRowCount() {
return personList.size();
}
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
public List<Person> getpersonList() {
return personList;
}
public void setPersonList(List<Person> personList) {
this.personList = personList;
fireTableDataChanged();
}
public void setPerson(Person sb){
personList.add(sb);
fireTableRowsInserted(personList.size()-1, personList.size()-1);
}
@Override
public String getColumnName(int index) {
return columnNames[index];
}
@Override
public int getColumnCount() {
return columnNames.length;
}
public String[] getColumnNames() {
return columnNames;
}
public void setColumnNames(String[] columnNames) {
this.columnNames = columnNames;
}
}
我想给JTable
我的数据对象列表以显示我的数据。我知道我可以将它们转换为Object[][]
来填充数据。但是,我想在我的桌面模型上做到这一点?
是否有一种优雅的方式将我的数据放在JTable中的TableModel上?
感谢您的回答!
答案 0 :(得分:1)
您必须在TableModel中实现Person Fileds的获取逻辑。
public class PersonTableModel extends AbstractTableModel {
private List<Person> people;
private static final int DATA = 0;
private static final int NAME = 1;
private static final int SURNAME = 2;
private static final int AGE = 3;
private static final String[] columns = new String[]{"Date", "Name", "Surname", "Age"};
private static final Class<?>[] clazz = {Date.class, String.class, String.class, Integer.class};
public PersonTableModel(List<Person> people) {
this.people = people;
}
@Override
public int getRowCount() {
return people.size();
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public String getColumnName(int columnIndex) {
return columns[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return clazz[columnIndex];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person a = getPerson(rowIndex);
if(a != null) {
switch (columnIndex) {
case DATA:
return a.getData().toGregorianCalendar().getTime();
case NAME:
return a.getName();
case SURNAME:
return a.getSurname();
case AGE:
return a.getAge();
}
}
return "";
}
public Person getPerson(int rowIndex) {
if (getRowCount() > rowIndex && rowIndex >= 0) {
return people.get(rowIndex);
}
return null;
}
}
方法getValueAt由表自动调用!
答案 1 :(得分:1)
从外观上看,您还没有实现 getValueAt 方法。这是获取将填充表格单元格的值的关键。
您的实现应该如下所示:
public Object getValueAt(int row, int col) {
Person person = personList.get(row);
switch (col) {
case 0:
return person.getName();
case 1:
return person.getBorndate();
case 2:
return person.getSalary();
case 3:
return person.getAge();
case 4:
return person.getCity();
default:
break;
}
}