I have data from the database on my JTable
. I want to add checkboxes to each row dynamically from the database. I will later use these checkboxes to delete rows checked from the database. I know how to delete from the database, but how to add checkboxes from the database? Any one done this before please help. I am a Java enthusiast trying to learn it. A sample code could help me understand how to do this.
Code below is for updating my JTable
:
public void UpdateTable() {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate", "root", "");
String sql = "SELECT certificate.Number, staff.Emp_Id, staff.Emp_Name, "
+ "staff.Department, certificate.Cert_Code, certificate.Cert_Name,\n"
+ "certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM staff LEFT JOIN certificate"
+ " ON staff.Emp_Id=certificate.Emp_Id ORDER BY staff.Emp_Name\n";
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Starting from this complete example, I made the changes below to get the following result. In particular,
Row
is given an attribute Boolean checked
, replacing String name
.
The default renderer uses a check box when getColumnClass()
returns Boolean.class
for Row.checked
.
In the corresponding JDBC and SQL, the checked
attribute is of type boolean
.
$ diff Original.java WorkerTest.java
48c48
< String name;
---
> Boolean checked;
91c91
< return row.name;
---
> return row.checked;
105a106,116
> @Override
> public Class<?> getColumnClass(int colIndex) {
> switch (colIndex) {
> case 0:
> return Integer.class;
> case 1:
> return Boolean.class;
> }
> return null;
> }
>
114c125
< r.name = rs.getString(2);
---
> r.checked = rs.getBoolean(2);
138c149
< st.execute("create table city(id integer, name varchar2)");
---
> st.execute("create table city(id integer, checked boolean)");
143,144c154
< ps.setString(2, (char) ('A' + r.nextInt(26))
< + String.valueOf(r.nextInt(1_000_000)));
---
> ps.setBoolean(2, Boolean.valueOf(r.nextBoolean()));