首页 > 代码库 > Table addColumn 引发的 ArrayOutOfBoundsException

Table addColumn 引发的 ArrayOutOfBoundsException

讲一下我这几天一直找不到原因的Exception, 如题,要多加一列时,出现ArrayOutOfBoundsException。

先上一下我要的效果图,第五列是新加的。

而且问题非常之“诡异”, 只出现在我已选定某行后, 才发生(假如未选定任何一行,是不会出现Exception的)

解决问题原来很简单,是ListSelectionEvent 和 tableModelEvent 那里需要多加个IF, 来排除 addColumn时对它们的影响。

那么就是这样:

 1 Public class myScrollPane extends JScrollPane implements ListSelectionListener { 2     /** 3      *  4      */ 5     private static final long serialVersionUID = 1L; 6     static JTable table; 7     private DefaultListSelectionModel selectionModel; 8     private static DefaultTableModel tableModel; 9     private static Vector<Object> data = http://www.mamicode.com/new Vector<Object>();10     private static Vector<String>  column_names = new Vector<String>();11     myScrollPane(){12         super();13         //database for table14         .....15 16         tableModel = new DefaultTableModel(){17             private static final long serialVersionUID = 1L;18 19             public Class<?> getColumnClass(int column) {20                 return (column==4)?(Boolean.class):(String.class);21             }22             23         };24         25         tableModel.setDataVector(data, column_names);26         table = new JTable(tableModel);27         table.setModel(tableModel);28         29         tableModel.addTableModelListener(new TableModelListener(){30             public void tableChanged(TableModelEvent arg0) {31                 //event‘s column == -1 occurs when adding a new column32                 if (arg0.getColumn()!=-1){33                     int Row = arg0.getFirstRow();34                     int Col = arg0.getColumn();35                     String new_value =http://www.mamicode.com/ table.getValueAt(Row, Col).toString() ;36                     proof_main.libreria.update_records(Row, Col, new_value);37                     38                 }39             }40             41         });42         43         44         setViewportView(table);45         //setting scrollpane46         setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);47         setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);48         49         selectionModel = new DefaultListSelectionModel();50         selectionModel.addListSelectionListener(this);51         selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);52         table.setSelectionModel(selectionModel);53     }54 55     public void valueChanged(ListSelectionEvent e) {56         int selectedRow = table.getSelectedRow();57         if (selectedRow!= (-1)) Main_panel.research_and_infoPanel.displayInfo(selectedRow);58         59     }

也就是第32行和第57行。

Table addColumn 引发的 ArrayOutOfBoundsException