Dor Cohen
Dor Cohen

Reputation: 117

how to Make only one column editable in JTable

I want to make my JTable unEditable but i want to add JButton to to it and the column of the button must be editable for the press event so how can i make this only column editable?

here is my table model code:

DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new String[]{ 
                                        "IDemp",
                                        "empNumber",
                                        "Fname","Lname",
                                        "BirthDate",
                                        "Address",
                                        "email",
                                        "Button" }
                                       );
//TableCellRenderer buttonRenderer = new JTableButtonRenderer();

for(int i=0;i<emps1.size();i++) {
    model.addRow(new Object[]{String.format("%d",emps1.get(i).getIDemp()),
                                String.format("%d",emps1.get(i).getEmpNumber()),emps1.get(i).getFname(),
                                    emps1.get(i).getLname(),emps1.get(i).getBirthDate(),
                                        emps1.get(i).getAddress(), emps1.get(i).getEmail().getEmailAddress()});
}

and here is my jtable:

JTable emps=new JTable(model);
emps.getColumn("Button").setCellRenderer(new ButtonRenderer());
emps.getColumn("Button").setCellEditor(new ButtonEditor(new JCheckBox()));

How could I make the "Button" column editable and the others not? *And if you have better way to add JButton to the JTable it will be great."

Upvotes: 1

Views: 2678

Answers (1)

Salah
Salah

Reputation: 8657

You need to extends the AbstractTableModel and override isCellEditable like this:

public class MyTableModel extends AbstractTableModel {

     public boolean isCellEditable(int row, int col) {
        if (col== columnIndex) { //columnIndex: the column you want to make it editable
            return true;
        } else {
            return false;
        }
    }
}

Upvotes: 4

Related Questions