在JTable Netbeans中插入单选按钮

时间:2012-02-02 18:20:05

标签: java swing jtable netbeans-6.9 jradiobutton

我使用Netbeans在JTable中填充员工数据。我想在每一行中添加Radiobutton,以便用户可以选择任何行并执行更新/删除等操作。 这是我的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);

在每行的第一列中,我想插入一个单选按钮。请建议我。 感谢。

2 个答案:

答案 0 :(得分:4)

我建议

  1. JRadioButton更改为JCheckBox,因为JCheckBox中的JTable仅代表Boolean

  2. 不要使用NetBeans生成的代码,手写代码

答案 1 :(得分:3)

您必须实施 TableCellEditor 并覆盖 getTableCellEditorComponent ,就像这样

public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)

{
            return new JRadioButton();
}

希望这有帮助

修改 你可以写这样的

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) {
    }

});

您可以将单元格编辑器实现取出到单独的类中。

此外,您必须根据您的要求设置标志。