简体   繁体   中英

how to set jcheckbox inside jtable dynamically

In this picture the return table head values show in the checkbox .

here jtable the values from database

I tried it but classcastexception occured because of boolean value cast to string

i don't know why that error occured

在此处输入图片说明

this is my code

    static Object[][] data;
String[] colName = {"Book", "Member", "Issue Date", "Return Date ",
        "Remark","Return" };

List<Issue>issues=ServiceFactory.getIssueServiceImpl().findAllIssue();
data=new Object[issues.size()][6];


for(Issue issue:issues){

    data[i][0]=issue.getMemberId().getName();
    data[i][1]=issue.getBookId().getName();
    data[i][2]=issue.getIssueDate();
    data[i][3]=issue.getReturnDate();
    data[i][4]=issue.getRemark();
    data[i][5]=issue.getStatus();

    i++;
}

here exception occured

 DefaultTableModel  dtm = new DefaultTableModel(data, colName);{
     public Class getColumnClass(int c) {
         switch (c) {
           case 0: return Boolean.class;
           default: return String.class;
         }   
       } };
 retunTable = new JTable();
 retunTable.setModel(dtm);
 retunTable.getTableHeader().setReorderingAllowed(false);


return retunTable;

if u know about this please share answers here...

edit

      DefaultTableModel dtm = new DefaultTableModel(data, colName);{
    public Class getColumnClass(int c) {
         switch (c) {
           case 0: return Boolean.class;
           default: return String.class;
         }   
       } };

     dtm .addRow(data); 
 retunTable = new JTable();
 retunTable.setModel(dtm);
 retunTable.getTableHeader().setReorderingAllowed(false);


return retunTable;

From you example and code, this looks wrong to me...

DefaultTableModel  dtm = new DefaultTableModel(data, colName);{
    public Class getColumnClass(int c) {
        switch (c) {
            case 0: return Boolean.class;
            default: return String.class;
        }   
    } 
};

Isn't column 0 "Book" ... or more importantanly, issue.getMemberId().getName()

Shouldn't it be...

DefaultTableModel  dtm = new DefaultTableModel(data, colName);{
    public Class getColumnClass(int c) {
        return c == 5 ? Boolean.class : String.class
    } 
};

Where column 5 is "Return"?

What you need is to use a cell editor for your JTable's cell. You can use DefaultCellEditor for your column and use the constructor that takes JTextField as input param.

for example, if your table's 2nd column needs to be a text field then you can do something like this:

TableColumn col2 = returnTable.getColumnModel().getColumn(1);
col2.setCellEditor(new DefaultCellEditor(new JTextField()));

For a detailed explanation See Oracle's tutorial for Table cell Editors

Hope this helps.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM