Проблема со вставкой строки в пользовательскую модель таблицы - PullRequest
0 голосов
/ 06 апреля 2011

У меня есть такая модель таблицы.

class GrvTableModel extends AbstractTableModel {

public String[] columnNames = ["Key" , "Value" ]
public Object[][] data = []

public selectedObjArray

    //Returns the number of columns in the datamodel
    public int getColumnCount() {
        return columnNames.length;
    }

    //Returns the number of rows in the datamodel
    public int getRowCount() {
        return data.length;
    }

    //Returns the name of column in the datamodel at the specified index
    public String getColumnName(int col) {
        return columnNames[col];
    }

    //Returns the name of column in the datamodel at the specified index
    def String getColumn(int colIndx) {
        return super.getColumn(colIndx)
    }
    //Returns the object at the specified [row,column] index
    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) {
        //Note that the data/cell address is constant,
        //no matter where the cell appears onscreen.
        if (col == 1) {
            return true;
        } else {
            return false;
        }
     }

//sets the object at the row and column as specified
    public void setValueAt(Object value, int row, int col) {
//        println "change table row: " + row

        data[row][col] = value;
        fireTableCellUpdated(row, col);
        selectedObjArray[row].val = value
    }

}

Мне нужно вставить пустую строку под выбранной строкой таблицы после нажатия на пункт меню «Вставить строку ниже» во всплывающем меню, которое появляется при щелчке правой кнопкой мыши по таблице. Для этого я сделал следующее.

class TablePopupImpl extends MouseAdapter implements ActionListener{
JPopupMenu tablePopup;
JMenuItem deleteCells,insertRowBelow;
public TablePopupImpl() {
tablePopup = new JPopupMenu()
deleteCells = new JMenuItem("Delete Cells")
insertRowBelow = new JMenuItem("Insert Rows below")
tablePopup.add(deleteCells)
tablePopup.add(insertRowBelow)
insertRowBelow.addActionListener(this)
}
public void mousePressed(MouseEvent e) {
    if (e.isPopupTrigger()) {
            tablePopup.show((Component)e.getSource(), e.getX(), e.getY());
    }
}
public void mouseReleased(MouseEvent e) {
    if (e.isPopupTrigger()) {
            tablePopup.show((Component)e.getSource(),e.getX(), e.getY());
    }
}
public void actionPerformed(ActionEvent e) {
    Object src=e.getSource()
    if(src.equals(insertRowBelow)){
                 DefaultTreeModel obj = (DefaultTreeModel)table.getModel() //error here
             obj.insertRow(table.getSelectedRow()+1,null)           
    }
}

}

Приведенные выше строки выдают ошибку, утверждающую, что GrvtableModel, т.е. моя пользовательская модель таблицы, не может быть преобразована в модель таблицы по умолчанию.

Чтобы добиться этого, я должен заменить приведение DefaultTreeModel приведением к Моей пользовательской модели таблицы.

GrvTableModel obj = (GrvTableModel)table.getModel()

и я должен написать метод внутри моей пользовательской табличной модели, который может добавить пустую строку ниже выбранной строки. Скажите, пожалуйста, как я могу написать такой метод / как мне выполнить мое требование?

1 Ответ

0 голосов
/ 06 апреля 2011

Как насчет использования List вместо массива?Затем вы можете просто вставить новую строку по указанному индексу.Однако вам, вероятно, потребуется каким-то образом перерисовать таблицу.

class GrvTableModel extends AbstractTableModel {

public String[] columnNames = ["Key" , "Value" ];
public List<Object[]> data = new ArrayList<Object[]>();

public selectedObjArray

    //Returns the number of columns in the datamodel
    public int getColumnCount() {
        return columnNames.length;
    }

    //Returns the number of rows in the datamodel
    public int getRowCount() {
        return data.size();
    }

    //Returns the name of column in the datamodel at the specified index
    public String getColumnName(int col) {
        return columnNames[col];
    }

    //Returns the name of column in the datamodel at the specified index
    def String getColumn(int colIndx) {
        return super.getColumn(colIndx)
    }
    //Returns the object at the specified [row,column] index
    public Object getValueAt(int row, int col) {
        return data.get(row)[col];
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

     public boolean isCellEditable(int row, int col) {
        //Note that the data/cell address is constant,
        //no matter where the cell appears onscreen.
        if (col == 1) {
            return true;
        } else {
            return false;
        }
     }

//sets the object at the row and column as specified
    public void setValueAt(Object value, int row, int col) {
//        println "change table row: " + row

        data.get(row)[col] = value;
        fireTableCellUpdated(row, col);
        selectedObjArray[row].val = value
    }

    public void insertNewRow(Object[] values, int row) {
        data.add(row, values);
        // Trigger a table update / redraw somehow.
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...