Adding JCheckBox into JTable

时间秒杀一切 提交于 2019-12-12 00:28:34

问题


I have a program to display database into a dynamic JTable. Its working fine. Now I want to add 1 more column into the table with CheckBox in each field. What should I do?

Here is my code:

public static DefaultTableModel myTableModel(ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = (ResultSetMetaData) rs.getMetaData();
    int columnsCount = metadata.getColumnCount();
    Vector<String> columnNames = new Vector<>();
    for (int i = 1; i < columnsCount; i++) {
        columnNames.add(metadata.getColumnName(i));
    }
    Vector<Object> data = new Vector<>();
    while (rs.next()) {
        Vector<Object> eachLine = new Vector<>();
        for (int i = 1; i < columnsCount; i++) {
            eachLine.add(rs.getObject(i));
        }
        data.add(eachLine);
    }
    return new DefaultTableModel(data, columnNames);
}

回答1:


okay.how i can add 1 more column ?.

You need to add a column for the name and for each row you add to the model. To add the columns at the beginning of the table you could do:

Vector<String> columnNames = new Vector<>();
columnNames.add("Boolean");
...
Vector<Object> data = new Vector<>();
data.add(new Boolean(false));

There is no need to create a custom renderer, but as others have mentioned you need to override the getColumnClass() method to return Boolean.class for that column so the table can use the appropriate renderer.




回答2:


Add a Boolean field if you want checkbox in JTable. False will be deselect and true value will represent selected checkbox. You can find Boolean column type while adding a JTable if you are a NetBeans user.

For more check this SO que.

How to add JCheckBox in JTable?



来源:https://stackoverflow.com/questions/21050164/adding-jcheckbox-into-jtable

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