java 如何删除jtable中的所有行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11625755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:50:07  来源:igfitidea点击:

how to remove all rows in jtable?

javaswingjtableactionlistenerselectionmodel

提问by Mr.Cool

i have one jtable with listselectionlistener i can dynamically added the new rows in to my table,when i select the row the selected row content will be appear in text box i can able to edit and remove the data ,for my application i stored the table data into xml file,when i add new row,that will be added into table successfully. but when i select a row and update means table doesn't get update(here i call load table()).( but updated values changed in xml file correctly) this my sample code for creating table*

我有一个带有列表选择侦听器的 jtable 我可以动态地将新行添加到我的表中,当我选择行时,所选行的内容将出现在文本框中我可以编辑和删除数据,对于我的应用程序,我存储了表将数据写入 xml 文件,当我添加新行时,该行将成功添加到表中。但是当我选择一行并更新意味着表没有得到更新(这里我调用加载表())。(但更新的值在 xml 文件中正确更改)这是我创建表的示例代码*

    ListSelectionModel selectionModel;
    JTable table1;
    model = new DefaultTableModel();
    table = new JTable(model);       table.setRowHeight(20);
    selectionModel = table.getSelectionModel();                  
    selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

 selectionModel.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {

            stxtBox.setText("");
            ptxtBox.setText("");
            ntxtBox.setText("");

            if (!e.getValueIsAdjusting()) {



             model1 = table.getSelectionModel();
                int lead = model1.getLeadSelectionIndex();
                int columns = table.getColumnCount();
                String sip = "";
                String sport = "";
                String snoq = "";
                for (int col = 0; col < columns; col++) {
                    Object o = table.getValueAt(lead, col);

                    if (col == 0) {
                        sip += o.toString();
                        stxtBox.setText(sip);
                        selectedip = sip;

                    } else if (col == 1) {

                        sport += o.toString();
                        ptxtBox.setText(sport);
                        selectedport = sport;
                    } else {

                        snoq += o.toString();
                        ntxtBox.setText(snoq);
                    }
                    selectedreq = snoq;

                }



            }table.clearSelection();
        }
    });

i load the table content like this

我像这样加载表格内容

  int rowCount=0;

            File file = new File("serverconfig.xml");

            if (file.exists())

            {

                System.out.print("in load");
                int e = table.getRowCount();

                if(e> 0)
                {

                while (table.getRowCount() > 0) {
                    ((DefaultTableModel) table.getModel()).removeRow(0);
                }

                }

//here i will load table content from my xml file (that's working fine)

the problem is when i update my table content i will call loadtable() function ever time i will get this error

问题是当我更新我的表格内容时我会调用 loadtable() 函数,每次我都会收到这个错误

java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
    at java.util.Vector.elementAt(Unknown Source)
    at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
    at javax.swing.JTable.getValueAt(Unknown Source)
    at Testsample.valueChanged(Testsample.java:1810)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
    at javax.swing.DefaultListSelectionModel.insertIndexInterval(Unknown Source)
    at javax.swing.JTable.tableRowsInserted(Unknown Source)
    at javax.swing.JTable.tableChanged(Unknown Source)
    at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
    at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
    at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
    at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
    at Testsample.loadtable(Testsample.java:577)
    at Testsample.actionPerformed(Testsample.java:1551)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)

回答by kleopatra

The old story: if there's high-level api to reach a goal, never-ever use the lower-level. Or maybe a related story: read the api doc, again and again :-)

老故事:如果有高级 api 来达到目标​​,永远不要使用低级。或者可能是一个相关的故事:一次又一次地阅读 api 文档:-)

For DefaultTableModel, the high-level api to remove all rows is:

对于 DefaultTableModel,删除所有行的高级 api 是:

model.setRowCount(0); 

Edit

编辑

Looking at your stacktrace, the error is not caused by the remove, but by accessing a newly added row.. My (random, without seeing more or your code :-) guess would be the rowIndex leadin

看你的堆栈跟踪,不被删除造成的错误,而是通过访问新添加的行。我的(随机的,没有看到更多的还是你的代码:-)猜测将是rowIndex位置lead

Object o = table.getValueAt(lead, col);

you'll have to check if its valid, might be negative (no lead) or still the old (index before adding) Note that the selection state is updated as a consequence of adding/removing data in the tableModel (as well as by user interaction) The important rule here is to be sure that table's internals are updated after model changes before accessing any state in client code. You can do so by wrapping it in invokeLater:

您必须检查它是否有效,可能是负数(无引导)或仍然是旧的(添加前的索引)请注意,选择状态是由于在 tableModel 中添加/删除数据而更新的(以及用户交互)这里的重要规则是确保在访问客户端代码中的任何状态之前,在模型更改后更新表的内部。您可以通过将其包装在 invokeLater 中来实现:

void updateTextBox() {
    if (selectionModel.getLeadSelectionIndex() >= table.getRowCount() ||
        selectionModel.getLeadSelectionIndex() < 0) return;
    .... // update text panel here
}

public void valueChanged(...) {
    if (e.getValueIsAdjusting()) return;
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
           updateTextBox();
        }
    }));
}

回答by mKorbel

for example

例如

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

public class RemoveAddRows extends JFrame {

    private static final long serialVersionUID = 1L;
    private Object[] columnNames = {"Type", "Company", "Shares", "Price"};
    private Object[][] data = {
        {"Buy", "IBM", new Integer(1000), new Double(80.50)},
        {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
        {"Sell", "Apple", new Integer(3000), new Double(7.35)},
        {"Buy", "Nortel", new Integer(4000), new Double(20.00)}
    };
    private JTable table;
    private DefaultTableModel model;

    public RemoveAddRows() {

        model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                int firstRow = 0;
                int lastRow = table.getRowCount() - 1;
                int width = 0;
                if (row == lastRow) {
                    ((JComponent) c).setBackground(Color.red);
                } else if (row == firstRow) {
                    ((JComponent) c).setBackground(Color.blue);
                } else {
                    ((JComponent) c).setBackground(table.getBackground());
                }
                /*if (!isRowSelected(row)) {
                String type = (String) getModel().getValueAt(row, 0);
                c.setBackground("Buy".equals(type) ? Color.GREEN : Color.YELLOW);
                }
                if (isRowSelected(row) && isColumnSelected(column)) {
                ((JComponent) c).setBorder(new LineBorder(Color.red));
                }*/
                return c;
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        JButton button1 = new JButton("Remove all rows");
        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                if (model.getRowCount() > 0) {
                    for (int i = model.getRowCount() - 1; i > -1; i--) {
                        model.removeRow(i);
                    }
                }
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            }
        });
        JButton button2 = new JButton("Add new rows");
        button2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                Object[] data0 = {"Buy", "IBM", new Integer(1000), new Double(80.50)};
                model.addRow(data0);
                Object[] data1 = {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)};
                model.addRow(data1);
                Object[] data2 = {"Sell", "Apple", new Integer(3000), new Double(7.35)};
                model.addRow(data2);
                Object[] data3 = {"Buy", "Nortel", new Integer(4000), new Double(20.00)};
                model.addRow(data3);
                System.out.println("model.getRowCount() --->" + model.getRowCount());
            }
        });
        JPanel southPanel = new JPanel();
        southPanel.add(button1);
        southPanel.add(button2);
        add(southPanel, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        RemoveAddRows frame = new RemoveAddRows();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

回答by sunil

this will do the task

这将完成任务

DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged();

for this to work you need to create table like this

为此,您需要像这样创建表

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)},
};

JTable jTable = new JTable();
jTable.setModel(new DefaultTableModel(data,columnNames));

回答by Peter

It's very easy: just do this:

这很简单:只需这样做:

DefaultTableModel model = (DefaultTableModel)table.getModel();

while(model.getRowCount() > 0){
   for(int i = 0 ; i < model.getRowCount();i++){
      model.removeRow(i);
   }
}