I am populating Employee Data in JTable using Netbeans. I want to add Radiobutton in each row, so that user can select any row and can perform actions like Update/Delete,etc. Here is my code for TableModel:
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new String[] {"Select","Employee ID","Name","Surname","Birth Place","Genre","Home","Marital Status","Phone","Age","Department"});
try{
con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/"+database,"root","123456");
Statement s = con.createStatement ();
s.executeQuery ("SELECT * FROM Employee");
ResultSet rs = s.getResultSet ();
rs.next ();
String eid = rs.getString ("emp_no");
String name = rs.getString ("name");
String surname = rs.getString ("surname");
String pbirth = rs.getString ("place_birth");
String genre = rs.getString ("genre");
String home = rs.getString ("home");
String mstatus = rs.getString ("marital_status");
String ph = rs.getString ("phone");
int age = rs.getInt ("age");
String dept = rs.getString ("department");
for(int i=0;i<30;i++)
model.addRow(new Object[] {?,eid, name, surname, pbirth, genre, home, mstatus, ph, age, dept});
}
catch (Exception e){
}
this.jTable1.setModel(model);
In first column of every row i want to insert a radiobutton. Please suggest me. thanks.
You have to implement TableCellEditor and override getTableCellEditorComponent like this
public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
return new JRadioButton();
}
Hope this helps
EDIT: You can write like this
this.jTable1.getColumnModel().getColumn(0).setCellEditor(new javax.swing.table.TableCellEditor(){
@Override
public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected, int row, int column) {
return new javax.swing.JRadioButton();
}
@Override
public java.lang.Object getCellEditorValue() {
return null;//Here you can return the radio button status
}
@Override
public boolean isCellEditable(java.util.EventObject anEvent) {
return false; //uneditable cell
}
@Override
public boolean shouldSelectCell(java.util.EventObject anEvent) {
return false;
}
@Override
public boolean stopCellEditing() {
return true;
}
@Override
public void cancelCellEditing() {
}
@Override
public void addCellEditorListener(javax.swing.event.CellEditorListener l) {
}
@Override
public void removeCellEditorListener(javax.swing.event.CellEditorListener l) {
}
});
You can take out the cell editor implementation to a separate class.
Also you have to set the flags accordingly to your requirement.
I'd suggest
change JRadioButton to JCheckBox, because JCheckBox in the JTable respresents only
Boolean
valuedon't use generated code from NetBeans, write code by your hands
来源:https://stackoverflow.com/questions/9117716/insert-radiobuttons-in-jtable-netbeans