删除所有行时JTable我得到java.lang.ArrayIndexOutOfBoundsException:-1如果选中该行

时间:2017-09-27 14:49:55

标签: java swing jtable

从表中删除所有行的合适方法是使用:

 DefaultTableModel tableModel = (DefaultTableModel) tablaPedidos.getModel();


        if (tableModel.getRowCount() > 0) {
            for (int i = tableModel.getRowCount() - 1; i > -1; i--) {
                tableModel.removeRow(i);
            }
        }

然而,在我的应用程序中,我有一系列tabbedPanes,例如tabbedPane 1和tabbedPane 2,tabbedPane 2包含一个JTable。我的目标是在窗格之间切换时清理JTable。

但是我得到了一个奇怪的功能,只有当JTable的所有行都没有被选中时才能正常工作,当在表中选择了一行然后我在tabbedPane 2中输入之后在tabbedPanes之间切换我得到了一个ListSelectionListener中的异常。

//If a row in the table was left selected when I switched between tabbedPanes I get a ArrayIndexOutOfBoundsException exception when running this code
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            if(!event.getValueIsAdjusting()) {
                String numeroPedido = table.getValueAt(table.getSelectedRow(), 0).toString();

            }
        }
    });


Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.Vector.elementData(Vector.java:730)
    at java.util.Vector.elementAt(Vector.java:473)
    at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:649)

我只是不知道选择一行来获得此异常的影响。

示例代码:

Container.java,包含两个TabbedPanes

package testClearTable;


import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JTabbedPane;


public class Container extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Container frame = new Container();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Container() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 926, 556);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        contentPane.add(tabbedPane, BorderLayout.CENTER);

        TabbedPane1 tabbedPane1 = new TabbedPane1();
        tabbedPane.addTab("TabbedPane1", null, tabbedPane1, null);

        TabbedPane2 tabbedPane2 = new TabbedPane2();
        tabbedPane.addTab("TabbedPane2", null, tabbedPane2, null);



        ChangeListener changeListener = new ChangeListener() {
              public void stateChanged(ChangeEvent changeEvent) {
                JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
                int index = sourceTabbedPane.getSelectedIndex();

                if(sourceTabbedPane.getTitleAt(index).equals("TabbedPane2")) {
                    Random r = new Random();
                    int randomNumber = r.nextInt(101);
                    TabbedPane2.updateTable(randomNumber);
                    System.out.println("Update table.");
                }


                System.out.println("Tab changed to: " + sourceTabbedPane.getTitleAt(index));
              }
            };

            tabbedPane.addChangeListener(changeListener);
    }


}

TabbedPane1.java

package testClearTable;

import javax.swing.JPanel;

public class TabbedPane1 extends JPanel {

    /**
     * Create the panel.
     */
    public TabbedPane1() {

    }

}

TabbedPane2.java

package testClearTable;

import java.util.ArrayList;

import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;




public class TabbedPane2 extends JPanel {
    private static JTable table;

    /**
     * Create the panel.
     */
    public TabbedPane2() {
        setLayout(new MigLayout("", "[][grow]", "[][grow]"));

        JScrollPane scrollPane = new JScrollPane();
        add(scrollPane, "cell 1 1,grow");

        table = new JTable();
        scrollPane.setViewportView(table);

        table.setModel(new DefaultTableModel(
                new Object[][] {
                },
                new String[] {
                    "Col 1", "Col 2", "Col 3"
                }
            ));

        addDummyData();

        table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent event) {
                if(!event.getValueIsAdjusting()) {
                    String numeroPedido = table.getValueAt(table.getSelectedRow(), 0).toString();

                }
            }
        });
    }

    public void addDummyData() {
        for(int i = 0 ; i < 10; i++) {
            Object [] fila = new Object[table.getModel().getColumnCount()];

            fila[0] = String.valueOf(i);
            fila[1] = String.valueOf(i);
            fila[2] = String.valueOf(i);


            ((DefaultTableModel) table.getModel()).addRow(fila);
        }   
    }

    public static  void addDummyData2(int k) {
        for(int i = 0 ; i < k; i++) {
            Object [] fila = new Object[table.getModel().getColumnCount()];

            fila[0] = String.valueOf(i);
            fila[1] = String.valueOf(i);
            fila[2] = String.valueOf(i);


            ((DefaultTableModel) table.getModel()).addRow(fila);
        }   
    }

    private static void clearTable() {
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();

        if (tableModel.getRowCount() > 0) {
            for (int i = tableModel.getRowCount() - 1; i > -1; i--) {
                tableModel.removeRow(i);
            }
        }
    }



    public static  void updateTable(int i) {
        clearTable();
        addDummyData2(i);
    }

}

2 个答案:

答案 0 :(得分:0)

在删除所有数据之前可能会调用JTable.clearSelection()吗?

答案 1 :(得分:0)

问题来自addListSelectionListener。 ListSelectionEvent已被触发,在清理表格并再次写入后,没有选择任何行。

        public void valueChanged(ListSelectionEvent event) {
            if(!event.getValueIsAdjusting()) {
                if(tablaPedidos.getSelectedRow() > -1) {

将验证添加到仅在选择实际行时执行操作时,我不会得到例外。

我不明白为什么再次清理和写入会触发ListSelectionEvent。