问题
I have created a JTable from data I stored in a SQL database. Basically, my number of columns are fixed in the JTable. Now I want to add a column which will allow the user to select a particular row using checkbox of that particular row.
I searched through the net I did not get any solution for this problem.
I searched in SO and all I got is how to add a column for JTable initialized using 2D array but not a SQL database.
I have attached the code which I am using to create my JTable. I think it is sufficient to understand my problem.
I have tried adding a column manually. It did add a column. But now my issue is that the checkboxes I assign to each row appear as javax.swing.JCheckBox instead of the "checkbox icon" in the column.
public void init_table(JTable X)
{
try
{
Class.forName(JDBC_DRIVER);
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/store",DB_USER, DB_PASS);
query="SELECT * from Stalk";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
DefaultTableModel model= new DefaultTableModel();
ResultSetMetaData meta = rs.getMetaData();
int Columncount = meta.getColumnCount();
for(int columnindex=1; columnindex<=Columncount; columnindex++)
{
model.addColumn(meta.getColumnLabel(columnindex));
}
Object[] row= new Object[Columncount];
while(rs.next())
{
int i=0;
for(i=0;i<Columncount;i++)
{
row[i]=rs.getObject(i+1);
}
model.addRow(row);
}
X.setModel(model);
}
catch(Exception e)
{
e.printStackTrace();
}
}
回答1:
Starting from this complete example, the changes below produce the result illustrated. Note:
The implementation of
getColumnClass()for theSELECTEDcolumn returns a type token ofBoolean.class, for which the default renderer uses a check box; more here.The
ResultSetincludes a new column of typeBoolean.The table
cityhas a new column of typeboolean, initialized to a random state.
$ diff OldTest.java WorkerTest.java
48a49
> Boolean selected;
91a93,94
> case 2:
> return row.selected;
105a109,121
> @Override
> public Class<?> getColumnClass(int colIndex) {
> switch (colIndex) {
> case 0:
> return Object.class;
> case 1:
> return String.class;
> case 2:
> return Boolean.class;
> }
> return null;
> }
>
114a131
> r.selected = rs.getBoolean(3);
138c155
< st.execute("create table city(id integer, name varchar2)");
---
> st.execute("create table city(id integer, name varchar2, selected boolean)");
140c157
< "insert into city values (?, ?)");
---
> "insert into city values (?, ?, ?)");
144a162
> ps.setBoolean(3, r.nextBoolean());
来源:https://stackoverflow.com/questions/55789445/how-do-i-add-a-column-of-jcheckbox-to-a-jtable-via-sql