我有一个 JTable,我在其中添加了一个 JButton(删除按钮)和一个 JComboBox 作为自定义单元格编辑器在两列上。现在,当我在 Combobox 中选择一个项目并单击 Delete 按钮时,选定的行将被删除,但已删除行的组合框会呈现在该行上。我是否也必须从表格中删除单元格编辑器。如果我不选择我的组合框,代码可以正常工作。请帮我。
这就是我的代码的样子:-
class JTableRenderer extends JButton implements TableCellRenderer, TableCellEditor{
private JComboBox sens_type_cb;
@Override
public Component getTableCellRendererComponent(final JTable table, Object value, final boolean isSelected, final boolean hasFocus, final int row, int column) {
if(column == 1)
{
System.out.println("Row " + row);
sens_type_cb = new JComboBox(new String[]{"Radar", "EO", "Aerial", "UAV", "Other"});
return sens_type_cb;
}
}
@Override
public void addActionListener(ActionListener listener)
{
sens_type_cb.addActionListener(listener);
}
@Override
public Component getTableCellEditorComponent(final JTable table, Object value, boolean isSelected, final int row, int column) {
if(column == 1)
{
ActionListener listen = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (table.isEditing())
table.getCellEditor().stopCellEditing();
//table.clearSelection();
}
};
sens_type_cb.addActionListener(listen);
return sens_type_cb;
}
else
return super.getParent();
}
public void addActionListener(ActionListener listener)
{
sens_type_cb.addActionListener(listener);
}
Next I create Class SensorConf in which I create a table:-
public class SensorConf extends javax.swing.JFrame {
private static SensorConf conf_obj = new SensorConf();
/* A private Constructor prevents any other class from instantiating. */
//private SensorConf(){ }
/* Static 'instance' method */
public static SensorConf getInstance( ) {
return conf_obj;
}
Action delete = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
((DefaultTableModel)table.getModel()).removeRow(modelRow);
}
};
public void CreateTable()
{
// jTable1.setModel(model);
jTable1.getColumn("S.No.").setPreferredWidth(40);
jTable1.getColumn("Sensor Type").setPreferredWidth(80);
jTable1.getColumn("").setPreferredWidth(40);
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getTableHeader().setReorderingAllowed(false);
jTable1.setRowHeight(25);
javax.swing.table.DefaultTableModel model = (javax.swing.table.DefaultTableModel)jTable1.getModel();
model.addRow(new Object[]{"", "", "", "", "", ""});
JTableRenderer tableRenderer = new JTableRenderer();
model.getRowCount();
model.setValueAt(new Integer(model.getRowCount()), model.getRowCount()-1,0);
jTable1.getColumnModel().getColumn(1).setCellEditor(tableRenderer);
jTable1.getColumnModel().getColumn(1).setCellRenderer(tableRenderer);
ButtonColumn buttonColumn = new ButtonColumn(jTable1, delete, 6);
}
private SensorConf() {
initComponents();
CreateTable();
}
我在 main 中实例化了我的类的一个对象,然后单击表外的添加按钮,我添加了一行 model.addRow(new Object[]{"", "", "", "", "", ""} ); 到我的桌子上。请帮助我找出我在哪里犯了错误。谢谢。