如何在JTable中设置JCheckbox可编辑?

时间:2018-02-01 10:27:14

标签: java swing jtable jcheckbox

我有JTable用于显示用户输入的值。使用班级'员工'我从用户那里获取值并在表格中显示它们。我使用了方法 getColumnClass() setValueAt() isCellEdditable 。我的程序的结果显示复选框但不允许我勾选方框: enter image description here

public class ETableModel extends AbstractTableModel {

    private boolean checked;

    private List<Employee> eDb;

    private String[] colNames = {"Select", "Name", "National Insurance Number", "National Insurance Catagory",
            "Contact number", "Email", "Address", "Town/City", "Postcode"};

    public String getColumnName(int column) {
        return colNames[column];
    }

    public ETableModel(){
    }

    public boolean isCellEdditable(int row, int col){
        switch(col){
        case 0:
            return true;
        default:
            return false;
        }
    }

    public void setData(List<Employee> eDB){
        this.eDb = eDB;
    }

    @Override
    public int getColumnCount() {
        return colNames.length;
    }

    @Override
    public int getRowCount() {
        return eDb.size();
    }

    @Override
    public Object getValueAt(int row, int col) {
        Employee employee = eDb.get(row);

        switch(col){
        case 0:
            return checked;
        case 1:
            return employee.getName();
        case 2:
            return employee.getnINumber();
        case 3:
            return employee.getnICatagory();
        case 4:
            return employee.getMobileNum();
        case 5:
            return employee.getEmail();
        case 6:
            return employee.getAddress();
        case 7:
            return employee.getArea();
        case 8:
            return employee.getPostCode();
        }
        return null;
    }

    @Override
    public void setValueAt(Object value, int row, int col){
        switch(col){
        case 0:
            checked = ((Boolean)value);
            fireTableCellUpdated(row, col);
        default:
            return;
        }
    }

    @Override
    public Class<?> getColumnClass(int col) {
        switch(col){
        case 0:
            return Boolean.class;
        case 1:
            return String.class;
        case 2:
            return String.class;
        case 3:
            return NICatagory.class;
        case 4:
            return Integer.class;
        case 5:
            return String.class;
        case 6:
            return String.class;
        case 7:
            return String.class;
        case 8:
            return String.class;
        default:
            return null;
        }
    }

}

有没有人有任何指针?我猜这个问题是在我的 setValueAt()方法中,但我不知道如何纠正这个问题。大多数示例都使用:

  

Data [int row] [int col] =((Boolean)value);

但是,当我从用户输入获取值时,我不确定如何使用它。

1 个答案:

答案 0 :(得分:1)

  

我猜这个问题是在我的 setValueAt()方法中

是的,在该方法中,您需要更新班级eDB中的成员ETableModel

另外,你拼写错误isCellEditable。这是拼写错误吗?如果不是,那么您需要更正您的代码。

祝你好运!