簡體   English   中英

從Arraylist中刪除對象

[英]Delete an object from Arraylist

我有一個對象的ArrayList(名稱,一些數字等),可以打開並在JTable上查看(名稱等)。 我可以將一個對象添加到jtable並將其添加到arraylist。 當我嘗試從JTable刪除對象時,它也不會在ArrayList上刪除。 我制作了這個ActionListener,並嘗試了兩種刪除Object的方法(使用remove()和迭代器)

    class ButtonRemovePersoAL implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            int numerorows = table.getSelectedRows().length;
            for(int i=0; i < numerorows ; i++ ) {
                String Name = (String) table.getModel().getValueAt(table.getSelectedRow(), 0); // I search for the first case of the JTable to catch the Object to erase
                for(Object object : myarraylistofobjects) {
                    if(Name.equals(object.getName())) {
                        myarraylistofobjects.remove(object);
                    }
                 }                  
                                  // OR
                Iterator<Object> itr = myarraylistofobjects().iterator();
                while (itr.hasNext()) {
                    Object object = itr.next();
                       if (Name.equals(object.getName())) {
                       itr.remove();
                    }

                }

                tablemodel.removeRow(table.getSelectedRow()); // I delete finally my row from the jtable
            }
        }

    }

我想念什么? 謝謝您的幫助。

讓我們從這里開始...

int numerorows = table.getSelectedRows().length;
for(int i=0; i < numerorows ; i++ ) {
    String Name = (String) table.getModel().getValueAt(table.getSelectedRow(), 0); // I search for the first case of the JTable to catch the Object to erase

基本上,您獲得選定行的數量,但是您只使用了第一個選定行的索引... table.getSelectedRow()

JavaDocs ...

返回值:
第一個選定行的索引

你應該做的是

for(int i : table.getSelectedRows()) {

它將遍歷每個選定的索引。

您應該避免這樣做...

String Name = (String) table.getModel().getValueAt(table.getSelectedRow(), 0);

由於視圖可能已排序,這意味着視圖索引(選定的行)不會直接映射到模型行,而是應使用

String name = (String) table.getValueAt(i, 0);

從這里開始,一切都變得有些混亂...

當你做類似的事情...

tablemodel.removeRow(table.getSelectedRow());

所有索引均不再有效(更不用說您不應該使用table.getSelectedRow()

相反,當您從ArrayList刪除該項目時,您應該記下它,然后遍歷TableModel來刪除刪除列表中的任何項目...

例如...

List<String> removedNames = new ArrayList<String>(25);
for(int i : table.getSelectedRows() ) {
    String name = (String) table.getValueAt(i, 0);
    removedNames.add(name);
    //...
}

int index = 0;
while (index < tableModel.getRowCount()) {
    Object value = tableModel.valueAt(index, 0);
    if (value != null && removedNames.contains(value.toString()) {
        tableModel.removeRow(index);
    } else {
        index++;
    }
}

坦率地說。 我更簡單的解決方案是創建一個自定義TableModel ,它是從AbstractTableModel擴展而來的,並將其包裹在ArrayList

如果您只想刪除一行

  myarraylistofobjects.remove(selectedRow) ;

  tablemodel.removeRow(table.getSelectedRow());

這兩行將解決您的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM