我应该首先告诉它,这不是关于渲染表格单元格.
这是我正在使用基于我的数据库中的User对象的2D数组构建的TableModel.
List<User> userList = userManagerService.getAllUsers(); /* String[] col_user = {"Username","Name","Phone",.... } */ String[][] data = new String[userList.size()][col_user.length]; int i = 0; for (User user : userList) { String[] userdata = new String[col_user.length]; userdata[0] = user.getUserUsername(); userdata[1] = user.getUserName(); userdata[2] = user.getUserPhone(); userdata[3] = user.getUserNic(); userdata[4] = user.getUserAddress(); userdata[5] = user.getUserEmail(); data[i++] = userdata; } VstTableItemModel tiModel = new VstTableItemModel(data,col_user); dataTable.setModel(tiModel);
我的问题是如何使用表中的选定行返回User对象.请注意,我无法创建新的User对象并使用行数据填充它.我必须获取查询的User对象(userList中的对象).那么,他们用表格行设置对象的方法是什么?
这是我的VstTableItemModel类.
public class VstTableItemModel extends AbstractTableModel { ArrayList<Object[]> data; String[] header; public VstTableItemModel(Object[][] obj,String[] header) { this.header = header; data = new ArrayList<Object[]>(); for (int i = 0; i < obj.length; ++i) { data.add(obj[i]); } } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return header.length; } @Override public Object getValueAt(int rowIndex,int columnIndex) { return data.get(rowIndex)[columnIndex]; } @Override public String getColumnName(int index) { return header[index]; } }
解决方法
在创建模型之前,不要将User对象拆分,而是将其直接添加到模型中,并允许模型为您完成工作…
例如
public class VstTableItemModel extends AbstractTableModel { private List<User> users; public VstTableItemModel(List<User> users) { this.users = new ArrayList<User>(users); } @Override public int getRowCount() { return users.size(); } @Override public int getColumnCount() { return 6; } @Override public Object getValueAt(int rowIndex,int columnIndex) { Object value = "??"; User user = users.get(rowIndex); switch (columnIndex) { case 0: value = user.getUserUsername(); break; case 1: value = user.getUserName(); break; case 2: value = user.getUserPhone(); break; case 3: value = user.getUserNic(); break; case 4: value = user.getUserAddress(); break; case 5: value = user.getUserEmail(); break; } return value; } @Override public Class<?> getColumnClass(int columnIndex) { return // Return the class that best represents the column... } /* Override this if you want the values to be editable... @Override public void setValueAt(Object aValue,int rowIndex,int columnIndex) { //.... } */ /** * This will return the user at the specified row... * @param row * @return */ public User getUserAt(int row) { return users.get(row); } }
这样,你应该可以做类似……
List<User> userList = userManagerService.getAllUsers(); VstTableItemModel tiModel = new VstTableItemModel(userList);
User user = tiModel.getUserAt(rowIndex);