简体   繁体   中英

assign a hidden value to each row of jTable

How can I assign an id to each row of jTable?
I don't want user be able to see it.

A quick hack is just to use a hidden column . A better method may be to write a custom table model that doesn't even expose said data to the JTable, but that is more involved :-)

Happy coding.

You should implement your own table model by creating a class that implements TableModel, or perhaps more easily create a class that extends AbstractTableModel.

If you do that then, you only need to implement

class MyModel extends AbstractTableModel {

    public Object getValueAt(int rowIndex, int columnIndex) {
        // return what value is appropriate  
        return null;  
    }

    public int getColumnCount() {
    // return however many columns you want
        return 1;
}

    public int getRowCount() {
    // return however many rows you want
    return 1;
}
}

typically you would create a List in the class of object of your choosing, and getRowCount would just be how big the list was.

getValueAt would return values from the Object in the list.

for instance If i wanted a table of users with a hidden id, it would be

class UserModel extends AbstractTableModel {

    private List<User> users = new ArrayList<User>();

    public Object getValueAt(int rowIndex, int columnIndex) {
        User user = users.get(rowIndex);
        if (columnIndex == 0)
            return user.getName();
        else
            return user.getAge(); //whatever 
    }

    public int getColumnCount() {
        return 2;
    }

    public int getRowCount() {
        return users.size();
    }
}

class User {
    private int userId; // hidden from the table
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

rowData只是一个Object数组,因此在表示行模型的类中,具有id的成员变量将不会包含在toString()中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM