當我運行(在運行或調試模式下)我的項目,我得到一個ArrayIndexOutOfBounds錯誤,這是有道理的。什麼不是,我檢查是否索引> = 0,儘管它說索引是-1,不知何故if內的代碼仍然運行。如果語句執行失敗
代碼:
...
// Contact List
lstContacts = new JList();
lstContacts.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lstContacts.setPreferredSize(new Dimension(200, 200));
lstContacts.setMinimumSize(new Dimension(50, 50));
_contactList = _dbi.GetContactList();
_selectedIndex = -1; // An int declared earlier
lstContacts.setListData(_contactList.toArray());
lstContacts.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
System.out.println();
System.out.println("lstContacts.getSelectedIndex: " + lstContacts.getSelectedIndex());
System.out.println("!e.getValueIsAdjusting: " + (!e.getValueIsAdjusting()));
System.out.println("getselectedindex > 0: " + (lstContacts.getSelectedIndex() > 0));
System.out.println("Both: " + (!e.getValueIsAdjusting() && (lstContacts.getSelectedIndex() > 0)));
// Filter out mid-actions
if(!e.getValueIsAdjusting() && (lstContacts.getSelectedIndex() > 0))
{
if(pnlDetail.isVisible())
{
saveCurrentContact();
}
else
{
pnlDetail.setVisible(true);
}
System.out.println(" Both: " + (!e.getValueIsAdjusting() && (lstContacts.getSelectedIndex() > 0)));
_selectedIndex = lstContacts.getSelectedIndex();
System.out.println(" _selectedIndex: " + _selectedIndex);
System.out.println(" lstContacts.getSelectedIndex: " + lstContacts.getSelectedIndex());
PersonalContact sc = (PersonalContact)_contactList.get(_selectedIndex); //crashes here
showContact(sc);
}
}
});
...
我插入列表中的三個虛擬接觸開始。點擊一個運行正常,但點擊另一個會拋出錯誤。在下面的錯誤中,我點擊了第二個條目。
控制檯輸出:
...
lstContacts.getSelectedIndex: 2
!e.getValueIsAdjusting: true
getselectedindex > 0: true
Both: true
Entry ID [2] modified.
lstContacts.getSelectedIndex: -1
!e.getValueIsAdjusting: true
getselectedindex > 0: false
Both: false
Both: false
_selectedIndex: -1
lstContacts.getSelectedIndex: -1
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at main.ContactPanel$2.valueChanged(ContactPanel.java:203)
at javax.swing.JList.fireSelectionValueChanged(Unknown Source)
at javax.swing.JList$ListSelectionHandler.valueChanged(Unknown Source)
... [continued]
它看起來像它運行正常,然後再次運行和崩潰。我錯過了什麼(可能是顯而易見的東西)?感謝您的時間和您可以提供的任何幫助。
這是在多個線程中運行? 如果條件爲真,那麼一旦您在if語句中索引被修改,這可能是原因。 –
@Moonfile - 看起來有多個線程在同一個對象上工作,這可能會導致此問題。 –
爲了儘快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –