I have worker for fill the jtable from resultset like below;
public class WorkerFillTable extends SwingWorker<DefaultTableModel, DefaultTableModel> {
private DefaultTableModel modeltable;
public WorkerFillTable(DefaultTableModel modeltable) {
this.modeltable = modeltable;
}
@Override
protected DefaultTableModel doInBackground() throws Exception {
ResultSet rs;
Statement stmt;
String query = "select Name,ID,Status,IsActive from current_conf\n" +
"order by Name,ID";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.130.100;" + "databaseName=DBST;" + "user=" + "user1" + ";" + "password=" + "userpass1" + ";";
Connection con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
Vector<String> columnNames = new Vector<String>();
int columnCount = rsmd.getColumnCount();
for (int column = 0; column < columnCount; column++) {
columnNames.addElement(rsmd.getColumnLabel(column + 1));
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
rs.close();
stmt.close();
modeltable = new DefaultTableModel(data, columnNames);
return modeltable;
}
@Override
protected void done() {
try {
TableModel modeltable = get();
sorter = new TableRowSorter(modeltable);
cTable.setRowSorter(sorter);
cTable.setModel(modeltable);
} catch (InterruptedException | ExecutionException ex) {
}
}
}
But all of columns come as String. "IsActive" columns of DB is a bit only have "1" or "0" Jtable shows this columns as "true" or "false" I need edit last column typr to boelan in jtable. How can i do it ?
I would recommend you to use a subclass of AbstractTableModel and override the getColumnClass method to set the correct data type for the JTable.
JDBCAdapter
, which extendsAbstractTableModel
, illustrates a typical mapping between relational database and Java data types. It may be seen here, and a complete example may be found insamples/demo/jfc/TableExample
, found among the Java SE Development Kit 8u25 Demos and Samples Downloads. In outline,Override
getColumnClass()
.Get the column's data
type
fromResultSetMetaData
.Use
switch(type)
to return the correct type-token.Also consider a
SwingWorker<Row, Row>
for finer granularity inpublish()/process()
.