下边的代码如何修改才能点一个按钮,就删除按钮所在的行????public class classgz extends JFrame{
public classgz()
{
     ...
     dtm = new DefaultTableModel(t1val,tt);
        
        jt=new JTable(dtm);
        jt.getColumnModel().getColumn(1).setCellRenderer(new JButtonRender());//为lasttc列设定一个渲染器
        jt.getColumnModel().getColumn(1).setCellEditor(new ButtonEditor(new JCheckBox()));设定一个编辑器
     ...
}public class ButtonEditor extends DefaultCellEditor {
   JButton button;
   String    label;
   boolean   isPushed;  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
        
      }
    });
  }  public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
       
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
       
    } else{
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value ==null) ? "" : value.toString();
    button.setText( label );
    isPushed = true;
    return button;
  }  public Object getCellEditorValue() {
    if (isPushed)  {
     
       
    }
    isPushed = false;
    return new String(  ) ;
  }
  
  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }    public void fireEditingStopped() {
    super.fireEditingStopped();
  }
}
    
    
    class JButtonRender extends JButton implements TableCellRenderer {
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
         
            
            if(isSelected)
        {
                 
        
            
         
            
        }
            else
        {
            setBackground(null);
              
        }
            
            if(hasFocus)
            {
               
                  if(column==1)
                  {
                    ((DefaultTableModel)table.getModel()).removeRow(row); 
                    this.transferFocusBackward();
                  }
                   
               
            
            }
        
            if(value==null)
            {
                setText("");
            }
            else
            {
                setText("选择");
            }            return this;
        }
        
    }
}
}

解决方案 »

  1.   

    此回复为自动发出,仅用于显示而已,并无任何其他特殊作用
    楼主【III_dont_know】截止到2008-07-11 13:41:44的历史汇总数据(不包括此帖):
    发帖的总数量:19                       发帖的总分数:500                      每贴平均分数:26                       
    回帖的总数量:16                       得分贴总数量:2                        回帖的得分率:12%                      
    结贴的总数量:18                       结贴的总分数:450                      
    无满意结贴数:1                        无满意结贴分:50                       
    未结的帖子数:1                        未结的总分数:50                       
    结贴的百分比:94.74 %               结分的百分比:90.00 %                  
    无满意结贴率:5.56  %               无满意结分率:11.11 %                  
    值得尊敬
      

  2.   

    这样吗?
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;public class classgz extends JFrame {    private DefaultTableModel dtm;    private JTable jt;    public classgz() {
            dtm = new DefaultTableModel();        jt = new JTable(10, 10);
            jt.getColumnModel().getColumn(1).setCellRenderer(new JButtonRender());// 为lasttc列设定一个渲染器
            jt.getColumnModel().getColumn(1).setCellEditor(new ButtonEditor(new JCheckBox()));// 设定一个编辑器
            jt.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    super.mouseClicked(e);
                    ((DefaultTableModel) jt.getModel()).removeRow(jt.getSelectedRow());
                }
            });
            this.getContentPane().add(new JScrollPane(jt));
        }    public class ButtonEditor extends DefaultCellEditor {
            JButton button;        String label;        boolean isPushed;        public ButtonEditor(JCheckBox checkBox) {
                super(checkBox);
                button = new JButton();
                button.setOpaque(true);
                button.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        // fireEditingStopped();                }
                });
            }        public Component getTableCellEditorComponent(JTable table,
                                                         Object value,
                                                         boolean isSelected,
                                                         int row,
                                                         int column) {            if (isSelected) {
                    button.setForeground(table.getSelectionForeground());
                    button.setBackground(table.getSelectionBackground());            } else {
                    button.setForeground(table.getForeground());
                    button.setBackground(table.getBackground());
                }
                label = (value == null) ? "" : value.toString();
                button.setText(label);
                isPushed = true;
                return button;
            }        public Object getCellEditorValue() {
                if (isPushed) {            }
                isPushed = false;
                return new String();
            }        public boolean stopCellEditing() {
                isPushed = false;
                return super.stopCellEditing();
            }        public void fireEditingStopped() {
                super.fireEditingStopped();
            }
        }    class JButtonRender extends JButton implements TableCellRenderer {
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {            if (isSelected) {            } else {
                    setBackground(null);            }            if (hasFocus) {                if (column == 1) {
                        // ((DefaultTableModel) table.getModel()).removeRow(row);
                        // this.transferFocusBackward();
                    }            }            if (value == null) {
                    setText("");
                } else {
                    setText("选择");
                }            return this;
            }    }    public static void main(String[] args) {
            JFrame frame = new classgz();
            frame.setVisible(true);
            frame.setSize(500, 500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
      

  3.   

    兄台,首先谢谢您给在下的指教,还望能继续给我指点!谢谢您的代码我放在netbeans5.5中运行后,我单击JTable中每行的任意单元格,都可以删除行,在下希望只单击到按钮上才删除行,另外还是会报如下错误码:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
            at java.util.Vector.elementAt(Vector.java:432)
            at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:637)
            at javax.swing.JTable.setValueAt(JTable.java:1875)
            at javax.swing.JTable.editingStopped(JTable.java:3333)
            at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:124)
            at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:329)
            at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:214)
            at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:3667)
            at javax.swing.JTable.editCellAt(JTable.java:2616)
            at javax.swing.plaf.basic.BasicTableUI$Handler.adjustFocusAndSelection(BasicTableUI.java:922)
            at javax.swing.plaf.basic.BasicTableUI$Handler.mousePressed(BasicTableUI.java:889)
            at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:222)
            at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:221)
            at java.awt.Component.processMouseEvent(Component.java:5485)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
            at java.awt.Component.processEvent(Component.java:5253)
            at java.awt.Container.processEvent(Container.java:1966)
            at java.awt.Component.dispatchEventImpl(Component.java:3955)
            at java.awt.Container.dispatchEventImpl(Container.java:2024)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3889)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
            at java.awt.Container.dispatchEventImpl(Container.java:2010)
            at java.awt.Window.dispatchEventImpl(Window.java:1766)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
      

  4.   

    很久以前写的,现在都快忘了,应该跟你的要求差不多吧,其实满足你的是
    private void delButtonActionPerformed(ActionEvent evt) {
            int index = tableName.getSelectedRow();
            if (index >= 0) {
                DefaultTableModel model = (DefaultTableModel) tableName.getModel();
                model.removeRow(index);
            }
        }
    判断行的索引是否大于零。如果不判断,可能会返回空指针异常,因为他还可以为null。import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    class ColumnName extends JFrame {
        static String[] columnName;//记录列名
        public ColumnName() {
            initComponents();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        private void initComponents() {
            cancelButton = new JButton();
            okButton = new JButton();
            buttonPanel = new JPanel();
            insertOneRow = new JButton();
            insertFiveRow = new JButton();
            delButton = new JButton();
            clearButton = new JButton();
            tablePanel = new JPanel();
            jScrollPane1 = new JScrollPane();
            tableName = new JTable();
            jLabel1 = new JLabel();
            jLabel2 = new JLabel();
            setTitle("列名");
            cancelButton.setText("取消");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    cancelButtonActionPerformed(evt);
                }
            });
            okButton.setText("确定");
            okButton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent evt) {
                    okButtonActionPerformed(evt);
                }
            });
            buttonPanel.setLayout(new GridLayout(4, 1, 0, 10));
            insertOneRow.setText("插入一行");
            insertOneRow.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent evt) {
                    insertOneRowActionPerformed(evt);
                }
            });
            buttonPanel.add(insertOneRow);
            insertFiveRow.setText("插入五行");
            insertFiveRow.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent evt) {
                    insertFiveRowActionPerformed(evt);
                }
            });
            buttonPanel.add(insertFiveRow);        delButton.setText("删除");
            delButton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent evt) {
                    delButtonActionPerformed(evt);
                }
            });
            buttonPanel.add(delButton);
            clearButton.setText("清屏");
            clearButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    clearButtonActionPerformed(evt);
                }
            });
            buttonPanel.add(clearButton);
            tablePanel.setBorder(BorderFactory.createTitledBorder("输入表名"));
            tableName.setModel(new DefaultTableModel(
                    new Object[][]{},
                    new String[]{
                        "列名"
                    }) {
                Class[] types = new Class[]{
                    java.lang.String.class
                };
                public Class getColumnClass(int columnIndex) {
                    return types[columnIndex];
                }
            });
            tableName.getTableHeader().setReorderingAllowed(false);
            jScrollPane1.setViewportView(tableName);        GroupLayout tablePanelLayout = new GroupLayout(tablePanel);
            tablePanel.setLayout(tablePanelLayout);
            tablePanelLayout.setHorizontalGroup(
                    tablePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, tablePanelLayout.createSequentialGroup().addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE).addContainerGap()));
            tablePanelLayout.setVerticalGroup(
                    tablePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(jScrollPane1, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE));        jLabel1.setText("最后输入完成后请按回车");        jLabel2.setText("以确保数据完整性");
    //**********************************
            GroupLayout layout = new GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addGroup(layout.createSequentialGroup().addComponent(okButton).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cancelButton)).addComponent(buttonPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addComponent(jLabel2).addComponent(jLabel1)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE).addComponent(tablePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addContainerGap()));
            layout.setVerticalGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(tablePanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(buttonPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 93, Short.MAX_VALUE).addComponent(jLabel1).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(jLabel2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(okButton).addComponent(cancelButton)))).addContainerGap()));
    //**********************************布局的,可以不看
            pack();
        }
        private void insertOneRowActionPerformed(ActionEvent evt) {
            DefaultTableModel model = (DefaultTableModel) tableName.getModel();
            Object ob[] = null;
            model.addRow(ob);
        }
        private void insertFiveRowActionPerformed(ActionEvent evt) {
            DefaultTableModel model = (DefaultTableModel) tableName.getModel();
            Object[][] ob = new Object[5][];
            for (int i = 0; i < ob.length; i++) {
                model.addRow(ob[i]);
            }
        }
        private void delButtonActionPerformed(ActionEvent evt) {
            int index = tableName.getSelectedRow();
            if (index >= 0) {
                DefaultTableModel model = (DefaultTableModel) tableName.getModel();
                model.removeRow(index);
            }
        }
        private void clearButtonActionPerformed(ActionEvent evt) {
            DefaultTableModel model = (DefaultTableModel) tableName.getModel();
            int rowNum = model.getRowCount();
            for (int i = 0; i < rowNum; i++) {
                model.removeRow(rowNum - i - 1);
            }
        }
        private void okButtonActionPerformed(ActionEvent evt) {
            System.exit(0);
        }
        private void cancelButtonActionPerformed(ActionEvent evt) {
            System.exit(0);
        }
        public static void main(String[] args) {
            ColumnName dialog = new ColumnName();
            dialog.setVisible(true);
        }
        private JPanel buttonPanel;
        private JButton cancelButton;
        private JButton clearButton;
        private JButton delButton;
        private JButton insertFiveRow;
        private JButton insertOneRow;
        private JLabel jLabel1;
        private JLabel jLabel2;
        private JScrollPane jScrollPane1;
        private JButton okButton;
        private JTable tableName;
        private JPanel tablePanel;
    }
      

  5.   

    汗,还可以抛出是否非法索引访问数组时抛出的异常,也就是ArrayIndexOutOfBoundsException。over~~~~~~~