使用AbstractTableModel在JTable中删除和添加行

时间:2016-02-16 19:39:52

标签: java swing jtable abstracttablemodel

我有一个严重的问题,从我的JTable中删除行,我的代码与我在学习AbstractTableModel时所看到的相同:

import javax.swing.table.AbstractTableModel;

public class MyTableModel extends AbstractTableModel {

             boolean DEBUG = true;

            input_Data input = new input_Data();
            String[] columnNames = {"First Name",
                      "Last Name",
                      "Sport",
                      "# of Years",
                      "Vegetarian"};
            Object[][] data = {
                {"Kathy", "Smith",
                    "Snowboarding", new Integer(5), new Boolean(false)},
                {"John", "Doe",
                        "Rowing", new Integer(3), new Boolean(true)},
                {"Sue", "Black",
                            "Knitting", new Integer(2), new Boolean(false)},
                {"Jane", "White",
                                "Speed reading", new Integer(20), new Boolean(true)},
                {"Joe", "Brown",
                                    "Pool", new Integer(10), new Boolean(false)};


                    public int getColumnCount() {
                        return columnNames.length;                  
                    }

                    public int getRowCount() {
                        return data.length;
                    }

                    public String getColumnName(int col) {
                        return columnNames[col];
                    }

                    public Object getValueAt(int row, int col) {
                        return data[row][col];
                    }
                    public Class getColumnClass(int c) {
                        return getValueAt(0, c).getClass();
                    }


                    public boolean isCellEditable(int row, int col) {

                        if (col < 2) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                    public void removeRow(Row)
                    {

                       fireTableRowsDeleted(Row,Row);

                    }
                }

但问题是当我调用removeRow时没有任何反应! 我想也许我也应该编辑数据,但是怎么样? 我是java的新手,我真的很喜欢这个问题......

1 个答案:

答案 0 :(得分:3)

您实际上并未使用此代码删除任何内容。不要将二维数组用于数据核心。使用ArrayList<CustomType>作为此类的数据核,实际删除 removeRow(int row)方法中此列表中的数据行,然后调用fireTableRowsDeleted(...)方法

相关问题