I have to 2 tables. JTable1
and Jtable2
. Jtable1 has data displayed from the database. Jtable2 should be having checkbox
for every row in Jtable1. I want number of rows in Jtable2 equal Jtable1. These 2 tables are beside eachother.
Here is an example:
In this example there is a checkbox beside every data item. I want a checkbox generated in JTable2
for every data item in Jtable1
.
Here is a picture to get a better idea:
Here is code:
public void fetch()
{
try
{
String sqlp = "select * from american";
pst = (OraclePreparedStatement) conn.prepareStatement(sqlp);
rs = (OracleResultSet) pst.executeQuery(sqlp);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
row =jTable1.getRowCount();
while(i!=row)
{
jTable2.add(check);
}
}
catch(Exception ex )
{
JOptionPane.showMessageDialog(null, ex);
}
}
jTable2.add(check);
You can't just add a JCheckBox to every row in the table. A table does not contain Swing components. It renders data contained in the TableModel
of the table.
You need to add data (representing a check box) to the TableModel
used by the table.
The DbUtils
class returns a TableModel
complete with data. So you have a couple of options:
DefaultTableModel
returned by the DbUtils
class and add a new column of data to the model. Read the DefaultTableModel
API. You can use the addColumn(...)
method to add a new column of data to the model. The column is added to the end of the model so you will then need to change the view of the table to display the column at the beginning of the table. You can use the moveColumn(...)
method of the JTable
to do this.
Finally when you create the JTable you will need to override the getColumnClass(...)
method to return Boolean.class
so the proper renderer/editor can be used.
Another option is to create a custom TableModel that wraps your current model with a checkbox. Check out: How to add checkbox in Jtable populated using rs2xml for an example of this approach
Finally, just don't use DbUtils, then you can be fully in control of the data in your TableModel. Check out: Java Resultset to JTable with Checkbox for an example of this approach.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.