How to set a custom object in a JTable row

我与影子孤独终老i 提交于 2019-11-29 10:39:09

Instead of splitting the User object up before you create the model, add it directly to the model and allow the model to do the work for you...

For example

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);
    }

}

This way, you should be able to do something like...

List<User> userList = userManagerService.getAllUsers();
VstTableItemModel tiModel = new VstTableItemModel(userList);

Now when you need to...you can grab a the user that is represent at a specific row...

User user = tiModel.getUserAt(rowIndex);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!