删除JTable的最后一行

时间:2014-02-16 21:26:48

标签: java swing jtable

我现场有点新鲜,我希望你们能帮助我......

我是java编程的初学者,我觉得我对这个问题感到非常满意。

我的程序工作正常,除了一个令我烦恼的小细节。我有一个JTable,第一列上有一个按钮,允许从表中删除该行。它工作得很好,除非我尝试删除表的最后一行,按钮停留在那里然后表冻结,我不能删除任何行,因为我收到“超出范围的异常”。但是,当我使用命令table.getRowCount());

在删除该行之前和之后,该表“知道”已删除一行但正如我所说,按钮停留在那里。缩略图中的屏幕截图显示了点击“年”单元格旁边按钮之前和之后的情况。

before after

最好补充说我是从表格外的按钮添加表格中的行。

继承我的代码: Main.java

static String [] title = {"X","Nom","SRM","Rend.","%","Kg",};
static Object[][] contenu;
static DefaultTableModel model1 = new DefaultTableModel(contenu, title);
static JTable tableauGrains = new JTable(model1);

tableauGrains.getColumn("X").setCellRenderer(new ButtonRenderer());
tableauGrains.getColumn("X").setCellEditor(new ButtonEditor(new JCheckBox()));

ButtonRenderer.java

import java.awt.Color;
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

public class ButtonRenderer extends JButton implements TableCellRenderer{

    public Component getTableCellRendererComponent( JTable table, Object value,
                                                    boolean isSelected, boolean isFocus,
                                                    int row, int col) {
        Color beige = new Color(218, 217, 158);
        setBackground(beige);
        //On écrit dans le bouton ce que contient la cellule
        setText((value != null) ? value.toString() : "");
        //on retourne notre bouton
        return this;
    }
}

ButtonEditor.java

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class ButtonEditor extends DefaultCellEditor {

    protected JButton button;
    private DeleteButtonListener bListener = new DeleteButtonListener();

    /**
     * Constructeur avec une checkBox
     * @param checkBox
     * @param count
     */
    @SuppressWarnings("deprecation")
    public ButtonEditor(JCheckBox checkBox) {
        //Par défaut, ce type d'objet travaille avec un JCheckBox
        super(checkBox);
        //On crée à nouveau notre bouton
        button = new JButton();
        button.setOpaque(true);
        //On lui attribue un listener
        button.addActionListener(bListener);

    }

      public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            //On précise le numéro de ligne à notre listener
            bListener.setRow(row);
            //Idem pour le numéro de colonne
              //On passe aussi le tableau en paramètre pour des actions potentielles
            bListener.setTable(table);

            //On réaffecte le libelle au bouton
            button.setText( (value == null) ? "" : value.toString() );
            //On renvoie le bouton
            return button;
          }

      class DeleteButtonListener implements ActionListener {

            private int row;
            private JTable table;

            public void setRow(int row){this.row = row;}
            public void setTable(JTable table){this.table = table;}

            public void actionPerformed(ActionEvent event) {
                if(table.getRowCount() > 0){
                //On affiche un message
                System.out.println("coucou du bouton: "+ ((JButton)event.getSource()).getText() );
                ((DefaultTableModel)table.getModel()).removeRow(this.row);
                    ((DefaultTableModel)table.getModel()).fireTableDataChanged();
                         }
          }
       }        
    }

我很抱歉法语评论,我的母语。

在删除最后一行之后,似乎JTable本身并没有“刷新”。

我是不是来自联盟?

非常感谢,对于这篇长篇文章感到抱歉,我试图给你最多的信息。

Djosimd 编辑:

  

删除后尝试单击第11行后执行堆   第12行:

     

线程“AWT-EventQueue-0”中的异常   java.lang.ArrayIndexOutOfBoundsException:11> = 11 at   java.util.Vector.elementAt(未知来源)at   javax.swing.table.DefaultTableModel.setValueAt(未知来源)at   javax.swing.JTable.setValueAt(未知来源)at   javax.swing.JTable.editingStopped(未知来源)at   javax.swing.AbstractCellEditor.fireEditingStopped(未知来源)at   javax.swing.DefaultCellEditor中的$ EditorDelegate.stopCellEditing(未知   来自)javax.swing.DefaultCellEditor.stopCellEditing(未知   来源)at   javax.swing.plaf.basic.BasicTableUI $ Handler.mousePressed(未知   来自)java.awt.AWTEventMulticaster.mousePressed(未知来源)     在java.awt.Component.processMouseEvent(未知来源)at   javax.swing.JComponent.processMouseEvent(未知来源)at   java.awt.Component.processEvent(未知来源)at   java.awt.Container.processEvent(未知来源)at   java.awt.Component.dispatchEventImpl(未知来源)at   java.awt.Container.dispatchEventImpl(未知来源)at   java.awt.Component.dispatchEvent(未知来源)at   java.awt.LightweightDispatcher.retargetMouseEvent(未知来源)at   java.awt.LightweightDispatcher.processMouseEvent(未知来源)at   java.awt.LightweightDispatcher.dispatchEvent(未知来源)at   java.awt.Container.dispatchEventImpl(未知来源)at   java.awt.Window.dispatchEventImpl(未知来源)at   java.awt.Component.dispatchEvent(未知来源)at   java.awt.EventQueue.dispatchEventImpl(未知来源)at   java.awt.EventQueue.access $ 200(未知来源)at   java.awt.EventQueue $ 3.run(未知来源)at   java.awt.EventQueue $ 3.run(未知来源)at   java.security.AccessController.doPrivileged(Native Method)at   java.security.ProtectionDomain $ 1.doIntersectionPrivilege(未知   来源)at   java.security.ProtectionDomain $ 1.doIntersectionPrivilege(未知   来自)java.awt.EventQueue $ 4.run(未知来源)at   java.awt.EventQueue $ 4.run(未知来源)at   java.security.AccessController.doPrivileged(Native Method)at   java.security.ProtectionDomain $ 1.doIntersectionPrivilege(未知   来自)java.awt.EventQueue.dispatchEvent(未知来源)at   java.awt.EventDispatchThread.pumpOneEventForFilters(未知来源)     at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)     在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知   来自java.awt.EventDispatchThread.pumpEvents(未知来源)     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)at   java.awt.EventDispatchThread.run(未知来源)


SSCCE:

import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import javax.swing.*;

public class FooGui {
   static String[] title = { "X", "Nom", "SRM", "Rend.", "%", "Kg"};
   static Object[][] contenu;
   // !! static DefaultTableModel model1 = new DefaultTableModel(contenu, title);
   static DefaultTableModel model1 = new DefaultTableModel(title, 0);

   static JTable tableauGrains = new JTable(model1);

   public static void main(String[] args) {
      tableauGrains.getColumn("X").setCellRenderer(new ButtonRenderer());
      tableauGrains.getColumn("X").setCellEditor(new ButtonEditor(new JCheckBox()));

      for (int i = 0; i < 10; i++) {
         String btnText = "Btn " + (i + 1);
         Object[] rowData = {btnText, "", "", "", "", ""};
         model1.addRow(rowData);
      }
      JOptionPane.showMessageDialog(null, new JScrollPane(tableauGrains));
   }
}

class ButtonRenderer extends JButton implements TableCellRenderer {

   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean isFocus, int row, int col) {
      Color beige = new Color(218, 217, 158);
      setBackground(beige);
      setText((value != null) ? value.toString() : "");
      return this;
   }
}

class ButtonEditor extends DefaultCellEditor {

   protected JButton button;
   private DeleteButtonListener bListener = new DeleteButtonListener();

   public ButtonEditor(JCheckBox checkBox) {
      super(checkBox);
      button = new JButton();
      button.setOpaque(true);
      button.addActionListener(bListener);
   }

   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
      System.out.printf("row is: %d%n", row);
      bListener.setRow(row);
      bListener.setTable(table);

      // On réaffecte le libelle au bouton
      button.setText((value == null) ? "" : value.toString());
      // On renvoie le bouton
      return button;
   }

   class DeleteButtonListener implements ActionListener {

      private int row;
      private JTable table;

      public void setRow(int row) {
         this.row = row;
      }

      public void setTable(JTable table) {
         this.table = table;
      }

      public void actionPerformed(ActionEvent event) {
         if (table.getRowCount() > 0) {
            System.out.println("coucou du bouton: " + ((JButton) event.getSource()).getText());
            ((DefaultTableModel) table.getModel()).removeRow(this.row);
            stopCellEditing();  // !! not sure if this will help or not.
            //!!  ((DefaultTableModel) table.getModel()).fireTableDataChanged();
         }
      }
   }
}

2 个答案:

答案 0 :(得分:3)

正如camickr所提到的那样,你忘记在删除行时停止单元格版本,这样就可以继续“编辑”单元格,并在不再存在的行上触发另一行删除(因此索引超出界限)例外)

最后取消按钮的版本。正如camickr所提到的,不需要fireTableDataChanged()removeRow()就可以解决这个问题。

请参阅SSCCE(实际上不是那么短,但我懒得修剪一些线条)进行演示:

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class TestJTable {

    public class ButtonEditor extends DefaultCellEditor {

        protected JButton button;
        private final DeleteButtonListener bListener = new DeleteButtonListener();

        /**
         * Constructeur avec une checkBox
         * 
         * @param checkBox
         * @param count
         */
        @SuppressWarnings("deprecation")
        public ButtonEditor(JCheckBox checkBox) {
            // Par défaut, ce type d'objet travaille avec un JCheckBox
            super(checkBox);
            // On crée à nouveau notre bouton
            button = new JButton();
            button.setOpaque(true);
            // On lui attribue un listener
            button.addActionListener(bListener);

        }

        @Override
        public Component getTableCellEditorComponent(JTable table,
                Object value, boolean isSelected, int row, int column) {
            // On précise le numéro de ligne à notre listener
            bListener.setRow(row);
            // Idem pour le numéro de colonne
            // On passe aussi le tableau en paramètre pour des actions
            // potentielles
            bListener.setTable(table);

            // On réaffecte le libelle au bouton
            button.setText(value == null ? "" : value.toString());
            // On renvoie le bouton
            return button;
        }

        class DeleteButtonListener implements ActionListener {

            private int row;
            private JTable table;

            public void setRow(int row) {
                this.row = row;
            }

            public void setTable(JTable table) {
                this.table = table;
            }

            @Override
            public void actionPerformed(ActionEvent event) {
                if (table.getRowCount() > 0) {
                    // On affiche un message
                    System.out.println("coucou du bouton: "
                            + ((JButton) event.getSource()).getText());
                    ((DefaultTableModel) table.getModel()).removeRow(this.row);
                    ButtonEditor.this.cancelCellEditing();
                }
            }
        }
    }

    private static final String[] title = { "X", "Nom", "SRM", "Rend.", "%",
            "Kg", };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestJTable().initUI();
            }
        });
    }

    protected void initUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DefaultTableModel model = new DefaultTableModel(title, 4);
        JTable table = new JTable(model);
        table.getColumn("X").setCellEditor(new ButtonEditor(new JCheckBox()));
        table.getColumn("X").setCellRenderer(new ButtonRenderer());
        frame.add(new JScrollPane(table));
        frame.pack();
        frame.setVisible(true);
    }

    public static class ButtonRenderer extends JButton implements
            TableCellRenderer {

        private static final Color beige = new Color(218, 217, 158);

        @Override
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean isFocus, int row,
                int col) {
            setBackground(beige);
            // On écrit dans le bouton ce que contient la cellule
            setText(value != null ? value.toString() : "");
            // on retourne notre bouton
            return this;
        }
    }

}

答案 1 :(得分:2)

虽然这不能解决您的问题,但请不要调用fireTableDataChanged,这是TableModel的工作。

问题出在TableEditor中。我猜你也不会停止细胞编辑。

结帐Table Button Column。它为您实现渲染器/编辑器。您需要做的就是在单击按钮时提供要调用的Action。