Im getting “Exception in thread “AWT-EventQueue-0” java.lang.ArrayIndexOutOfBoundsException:0
and I really dont understand why.
I have these two inner classes that I use as Listeners for a JPanel called bildYta:
private class NyPlatsLyss implements ActionListener{
public void actionPerformed(ActionEvent e){
bildYta.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
bildYta.addMouseListener(new BildYtaLyss());
bildYta.addKeyListener(new EscLyss());
bildYta.requestFocusInWindow();
enableOperations(false);
}
}
private class EscLyss extends KeyAdapter{
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ESCAPE){
bildYta.setCursor(Cursor.getDefaultCursor());
bildYta.removeMouseListener(bildYta.getMouseListeners()[0]);
bildYta.removeKeyListener(this);
enableOperations(true);
}
}
}
When I press a button it adds both of the listeners to bildYta. What I do not understand is why I get .ArrayIndexOutOfBoundsException:0 when I remove the mouse listener that I just added. Sometimes I dont even get an exception, and sometimes I do. Nothing in the rest of my code should cause any trouble because after I add those listeners, nothing else is supposed to happen in my program. It waits for either and ESC press or a mouse click
This is very fragile code. The event handled by
EscLyssmay fire several times and only the first time it will work. Add some checks to your code. Even better, save yourEscLyssinstance to a field and then remove that specific instance directly. Better still, make that instance final and you can reuse it, repeatedly adding and removing it as needed. That is, in fact, the way we typically do it.