0

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);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
RAJIL KV
  • 399
  • 1
  • 7
  • 24
  • I don't think showing us that piece of code will be much help. I do think you would find it more clear if you wrote your own `TableModel` though. You should create your own [TableCellRenderer](http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableCellRenderer.html). – Josh M Jan 10 '14 at 17:05
  • Like [this](http://stackoverflow.com/a/4528604/230513)? – trashgod Jan 10 '14 at 17:08
  • okay.how i can add 1 more column ?. – RAJIL KV Jan 10 '14 at 17:09
  • You should read on JTables, http://docs.oracle.com/javase/tutorial/uiswing/components/table.html, you'll find a section on Using Custom Renderers – P. Lalonde Jan 10 '14 at 17:10

2 Answers2

3

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

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?

Community
  • 1
  • 1
Not a bug
  • 4,286
  • 2
  • 40
  • 80
  • 3
    Note that should be Boolean, not boolean, since the model holds reference types, and the `getColumnClass(int columnIndex)` method override should return Boolean.class for that column. – Hovercraft Full Of Eels Jan 10 '14 at 17:36