Problem with remove() method of ArrayList collection

Dear All,
I have a program below: See the statement in bold
//Start of the Program
import java.util.*;
public class ArrayListTest
     public static void main(String args[])
          //declare an arraylist of type String
          List<String> stringStorage = new ArrayList<String>();
          //add elements to the ArrayList
          stringStorage.add("apple");
          stringStorage.add("banana");
          stringStorage.add("papaya");
          stringStorage.add("peach");
          stringStorage.add("cucumber");
          stringStorage.add("orange");
          stringStorage.add("grapes");
          stringStorage.add("plum");
          stringStorage.add("chiku");
          stringStorage.add("pomegrenate");
          stringStorage.add("pomegrenate2");
          //iterate through the ArrayList
          Iterator<String> iterate = stringStorage.iterator();
          //test whether an element is present
          boolean isPresent = stringStorage.contains("xxx");
          System.out.println("xxx is Present "+isPresent);
          //remove an element from the ArrayList
Line no: 12     System.out.println("Remove apple:(true/false)"+stringStorage.remove("apple"));
          Loop:
          for (int i=0;i<stringStorage.size();i++)
               while (iterate.hasNext()==true)
                    System.out.println("Element in the arraylist["+i+"] "+iterate.next());
                    //iterate.remove();
                    continue Loop;
End of Outer Loop:
//End of the Program
It compiles fine. But when I try to run , it gives a unchecked exception in main ConcurrentModificationException.
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at ArrayListTest.main(ArrayListTest.java:48)
But, if I remove Line no 12(in bold), or put the same statement after End of Outer Loop: , I do not get the error. Can you explain this phenomenon?

look what you do:
1/ you retrieve the iterator
2/ you remove apple
3/ you browse the iterator
but actually, the iterator kept a reference to the "apple" you just removed ; that s why it gets screwed ;
you mustn't operate on the list if you re not over with the iterator work

Similar Messages

  • Problem with remove method

    Hi:
    I have written a Calendar program that will add appointments and then print the appointment list. I need to write code to remove selected appointments. How do I make reference to the appointment objects I created in the test portion of my program so that I can remove them with the removeApp method(code not written yet)?
    Describes a calendar for a set of appointments.
    @version 1.0
    import java.util.Vector;
    public class CalendarTest
    {  public static void main(String[] args)
         Calendar markCalendar = new Calendar("Mark");
         markCalendar.addApp(new Appointment("June 1","3pm","4pm", "dentist"));
          markCalendar.addApp(new Appointment("June 2","3pm","4pm", "doctor"));
         markCalendar.print();
          //markCalendar.removeAppz(Appointment(1));does not work
    Describes a calendar for a set of appointments.
    class Calendar
      Constructs a calendar for the person named.
      public Calendar(String aName)
      {  name = aName;
         appointments = new Vector();
      Adds an appointment to this Calendar.
      @param anApp The appointment to add.
      public void addApp(Appointment anApp)
         appointments.add(anApp);
      Removes an appointment from this Calendar.
      @param anApp The appointment to be removed.
      public void removeApp(Appointment anApp)
         appointments.remove(anApp);//does not work
      Prints the Calendar.
      public void print()
      {  System.out.println(name + "               C A L E N D A R");
         System.out.println();
          System.out.println("Date   Starttime    EndTime   Appointment");
         System.out.println("vector size" + appointments.size());
         appointments.remove(0);
         for (int i = 0; i < appointments.size(); i++)
         {  Appointment nextApp =(Appointment) appointments.get(i);
            nextApp.print();
      private Vector appointments;
      private String name;
      private Appointment theAppointment;
    Describes an appointment.
    class Appointment
      public Appointment(String aDate,String aStarttime,String aEndtime, String aApp)
      {  date = aDate;
         starttime = aStarttime;
          endtime = aEndtime;  
         app = aApp;
      Prints the Date, Starttime, Endtime and a description of the
      appointment.
      public void print()  
      {  System.out.println();
         System.out.println(date + "   " + starttime + "          " + endtime
             + "       " + app );
         System.out.println();
      private String date;
      private String starttime;
      private String endtime;
      private String app;

    //markCalendar.removeAppz(Appointment(1));
    Will not work, what object are you trying to pass to your method?
    I assume you want to remove an Appointment from appointments?
    You could make the Vector appointments public and use markCalendar.appointments(1) or make a method to return the Vector and then choose an Appoinment to pass to your removeApp() method.

  • Problem with traverse method

    Hi, I am having this problem:
    I made a CustomItem, a TextField, now I overloaded the traverse method, so if the keycode is Canvas.UP or Canvas.DOWN then return false else return true.
    The problem is that when I press the left or rigth button it also returns false and not true.
    and there is another problem with traverse, before returning false or true I set a boolean and call to repaint to draw it on some way if its selected or not, the paint method is being called but it just dont draw as desired.
    protected void paint(Graphics g, int ancho, int alto) {
              System.out.println ("Dentro del paint, seleccionado="+seleccionado);
              try {
                   g.drawString(label, 0, 0, Graphics.TOP|Graphics.LEFT);
                   if (!seleccionado) {
                        g.setColor(120, 120, 120);
                   g.drawRect(0, 4, tama�oTexto+8, 25);
                   if (seleccionado) {
                        g.setColor(255, 255, 255);
                        g.fillRect(1, 5, (tama�oTexto+8-1), 23);
                   g.setColor(0, 0, 0);
                   if (!seleccionado) {
                        g.setColor(80, 80, 80);
                   g.drawString(texto, 4, 7, Graphics.TOP|Graphics.LEFT);
                   if (seleccionado) {
                        int cursorX=Font.getDefaultFont().charsWidth((texto.substring(0, idLetraActual)).toCharArray(), 0, texto.substring(0, idLetraActual).length())+4;
                        g.drawChar('|', cursorX, 7, Graphics.TOP|Graphics.LEFT);
              } catch (Exception E){
                   E.printStackTrace();
         }the traverse method set the seleccionado variable and calls to repaint but instead of being false the paint method is drawing it as true (most of times).

    I have a problem with findByxxx() method.. in
    Container managed bean.
    i have
    Collection collection =
    home.findByOwnerName("fieldValue");
    specified in my Client Program, where ownerName is the
    cmp fieldname..
    and
    public Collection findByOwnerName(String ownerName)
    throws RemoteException, FinderException
    defined in my home interface.
    i have not mentioned the findBy() method anywhere else
    (Bean class). You have to describe the query in the deployment descriptor.
    >
    Even if i have a same "fieldValue" in the database
    (Oracle), which i specified in findBy() method, iam a
    result of owner Not found, which is not the case as i
    have that owner name.
    for the same application if i use findByPrimaryKey(),
    it is working..
    Can any one please post me the solution.

  • I have problem with pay method

    I have problem with pay method. My card declined. I change card and I have the same problem. What can i do? Why declined my card again?

    Contact iTunes store support: https://ssl.apple.com/emea/support/itunes/contact.html.

  • Problem with prerender method

    Hi,
    I have a problem with the method prerender. A month ago, I started to develop a web project using Sun Studio Creator and a few page beans that i used extended the Abstract Page Bean, so I overrided the prerender and customized it.
    The problem is that, now i'm using eclipse and the configuration files of the project has changed and the prerender method never execute.
    I want to know why it is happening. Maybe the project is "bad-configurated"?
    Thanks

    The code of java bean doesn't change, the only thing that has changed is the configuration files (faces-config.xml, web.xml, etc).
    I put a breakpoint in the prerender method but the lifecycle doesn�t execute this method.
    After serveral changes, I wrote this code in the method prerender :
    int i=0;
    i = 1;
    And the prerender method doesn't execute.
    I'm a bit lost,
    thanks

  • Problem with affinetransformOp method...

    I have a serious problem with filter method
    I Want to make a image flipping or some other filtering by using
    AffineTransformOp
    but it printouts an erro like this
    cannot resolve symbol
    op.filter (img, flipped)
    (the error pointer shows ".after the op")
    a code from my one of the filters
    BufferedImage flipped = new BufferedImage(img.getHeight(), img.getWidth(),BufferedImage.TYPE_INT_RGB);
    AffineTransform trans = new AffineTransform(0, 1, 1, 0, 0, 0);
    AffineTransformOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    op.filter(img, flipped); //img is my buffered image source
    I used some other ways like (img, null) but always give out error.
    thanks..

    Did you declare "img" as BufferedImage or something else?
    What is the full error message?

  • Problem with WindowClosing() method

    Hello everyone,
    I have some problem with WindowClosing() method, in which I gave options
    to quit or not. Quit is working fine but in case of Cancel, its not returning to
    the frame. Can anyone help me ....Here is my code
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class TestFrame extends JPanel
         public static void main(String[] args)
              JFrame frame = new JFrame("Frame3");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        int button = JOptionPane.showConfirmDialog(null,"OK to Quit","",JOptionPane.YES_NO_OPTION, -1);
                        if(button == 0)     {
                             System.exit(0);
                                   else
                                              return;
              frame.addWindowListener(l);
              frame.setSize(1200,950);     
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }

    Maybe try
    int button = JOptionPane.showConfirmDialog(yourframe,"OK to
    Quit","",JOptionPane.YES_NO_OPTION, -1);

  • Problem with remove task from schedule in PWA

    In our environment problem with remove task from schedule by PWA.
    Problem is only when I want to remove few task in the same time, but the operation one by one is correct.
    In my opinion problem is with calculation schedule after remove tasks, column ID include wrong value it means that Number ID does not generate in the correct order same of numer
    disappear. Click Calculate button on ribbon causes problem with finshed operation and save project.
    Problem occurs only machine with IE 11.0 browser without compability mode, on other machine for example on the same project with IE 8,9,10 everything is correct.
    Problem appeared recently, earlier everything was OK.
    Txn, Dariusz Moczyński

    Hi Darius,
    I'm a bit confused. You are now talking about 2 issues.
    For the first one, you cannot edit anymore tasks in PWA, with any browser versions? Is it happenonog for any users on any projects? Try the following solutions publish the project from Project Pro and see if it helps. Press CTRL F5 to delete IE cache. Ensure
    that your PWA URL is added to the trusted site and/or compatibility sites. Check for the ULS logs or javascript errors.
    For the second issue, please refer to my previous reply, this obviously cannot be considered as a bug since it is happening with a non supported browser version and working properly on supported versions of IE.
    Hope this helps,
    Guillaume Rouyre, MBA, MVP, P-Seller |

  • Problem with SQL connection and a Collection

    hi all,
    I have two problems with sql...
    1. how can I assign the values of a resultset to a collection?
    2. how can I close the sql connection, because when I close the statement and connection error shows me in the resultset
    thanks!

    Hello Pablo,
    RetrivingResults In Collection:
    1)   use getObject method, and assign it to collection.
              Collection c_obj=new ArrayList();
             while(rs.next())
                    c_obj.add(rs.getInt(Project_ID), rs.getString(Project_Name));
    Closing ResultSet
    2)               The close() methos of ResultSet closes the ResultSet object, like bellow
                    ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
                    rs.close(); //Closes the result set

  • Problem with binarySearch method

    In the code below I've got a problem with my binarySearach method in the IntegerList.java file. When I look at my IntegerTest file, Eclipse give me this message next to my method call for the binarySerch (case 6): (the method binarySearch int[] , int) in the type integerList is not applicable for the arguments (int). So what the heck have I done wrong? I know it's a lot of code to look at but felt you'll need to see both classes to make heads or tales out of this.
    Thanks in advance.
    import java.util.Scanner;
    public class IntegerList //implements Comparable
         int [] list; // values in the list
         //Constructor -- takes an integer and creates a list of that
         //size.  All elements default to value 0.
         public IntegerList(int size)
              list = new int[size];
         //randomize -- fills the array with randomly generated integers
         //between 1 and 100, inclusive
         public void randomize()
              int max = list.length;
              for (int i=0; i < list.length; i++)
                   list[i] = (int) (Math.random() * max) +1;
         //fillSorted -- fills the array with sorted values
         public void fillSorted()
              for (int i =0; i <list.length; i++)
                   list = i + 2;
         //print -- prints array elements with indices, one per line
         public String toString()
              String s = "";
              for (int i = 0; i <list.length; i++)
                   s += i + ":\t" + list[i] + "\n";
              return s;
         //linearSearch -- takes a target value and returns the index
         //of the first occurrence of target in the list. Returns -1
         //if target does not appear in the list
         public int linearSearch (int target)
              int location = -1;
              for (int i = 0; i < list.length && location == -1; i++)
                   if (list [i] == target)
                        location = i;
                   return location;
         //sortIncresing -- uses selection sort
         public void sortIncreasing()
              for (int i =0; i < list.length -1; i++)
                        int minIndex = minIndex(list, i);
                        swap (list, i, minIndex);
    private void swap(int[] list, int index, int min)
    int temp =list [index];
    list [index] = list [min];
    list [min] = temp;
    // private int minIndex(int[] list, int index)
    public int minIndex(int[] list, int lastIndex) {
    int min=list[lastIndex];
    for (int i=lastIndex+1; i<list.length; i++)
    if (list[i]<min)
    lastIndex=i;
    return lastIndex;
    public void sortDecreasing()
              for (int i =0; i > list.length -1; i++)
                        int minIndex = minIndex(list, i);
                        swap (list, i, minIndex);
    public static int binarySearch (int [] list, int val)
    int min = 0, max = list.length, mid =0;
    boolean found = false;
    while (!found && min <= max)
    mid = (min + max) / 2;
    if (list [mid]== val)
    found = true;
         //if the mid point contains the value being searched for
         //then we are done
    else
    if (list[mid]< val)
    max = mid -1;
    else
    min = mid+1;
    if (found)
    return list[mid];
    else
    return -1;
    return val;
    }//end class
    //now for the IntegerListTest class
         //File: integerListTest.java
         //Purpose: Provide a menu-driven tester for the IntegerList class.
         import java.util.*;
         public class IntegerListTest
              static IntegerList list = new IntegerList(10);
              static Scanner scan = new Scanner(System.in);
         // main -- creates an initial list, then repeatedly prints
         // the menu and does what the user asks until they quit
         public static void main(String [] args)
              printMenu();
              int choice = scan.nextInt();
              while (choice != 0)
                        dispatch(choice);
                        printMenu();
                        choice = scan.nextInt();
         // dispatch -- takes a choice and does what needs doing
         public static void dispatch(int choice)
              int loc;
              int val;
              long time1, time2;
              long totalTime;
              switch (choice)
                        case 0:
                             System.out.println("Bye!");
                             break;
                        case 1:
                             System.out.println(list);
                             break;
                        case 2:
                             System.out.println("How big should the list be?");
                             list = new IntegerList (scan.nextInt());
                             System.out.println("List is created.");
                             break;
                        case 3:
                             list.randomize();
                             System.out.println("List is filled with random elements.");
                             break;
                        case 4:
                             list.fillSorted();
                             System.out.println("List is filled with sorted elements.");
                             break;
                        case 5:
                             System.out.print("Enter the value to look for: ");
                             val = scan.nextInt();
                             time1 = System.currentTimeMillis();
                             loc = list.linearSearch(val);
                             time2 = System.currentTimeMillis();
                             totalTime = time1 - time2;
                             System.out.print(totalTime);
                             if (loc != -1)
                                  System.out.println("Found at location " + loc);
                             else
                                  System.out.println("Not in list");
                             break;
                        case 6:
                             System.out.print("Enter the value to look for: ");
                             val = scan.nextInt();
                             loc = list.binarySearch(val);
                             if (loc != -1)
                                  System.out.println("Found at location " + loc);
                             else
                                  System.out.println("Not in list");
                             break;
                        case 7:
                             list.sortIncreasing();
                             System.out.println("List has been sorted.");
                             break;
                        case 8:
                             list.sortDecreasing();
                             System.out.println("List has been sorted.");
                             break;
                        default:
                             System.out.println("Sorry, invalid choice");
         // printMenu -- prints the user's choices
         public static void printMenu()
              System.out.println("\n Menu ");
              System.out.println(" ====");
              System.out.println("0: Quit");
              System.out.println("1: Print the list");
              System.out.println("2: Create a new list of a given size");
              System.out.println("3: Fill the list with random ints in range 1-length");
              System.out.println("4: Fill the list with already sorted elements");
              System.out.println("5: Use linear search to find an element");
              System.out.println("6: Use binary search to find an element " +
                                  "(list must be sorted in increasing order)");
              System.out.println("7: Use selection sort to sort the list into " +
                                  " increasing order");
              System.out.println("8: Use insertion sort to sort the list into " +
                                  " decreasing order");
              System.out.println("\nEnter your choice: ");

    Ah... But now that I have looked at it some more, I have noticed that the array of int is created in your IntegerList class...
    so you want to change your binarySearch() method...
    from...
    public static int binarySearch (int[] list,int val)to
    public int binarySearch (int val)now it will search the list declared in your constructor...
    and also note that static is remove to eliminate the non-static reference from static context error...
    so in IntegerList.java, that method signature should look like this...
    public int binarySearch (int val)// take only one arguement and...
    // check against internal int [] listand you call it like this...
    loc = list.binarySearch(val);// not changednow all you have to do it get your list populated with random integers for the rest to work... I leave that to you...
    - MaxxDmg...
    - ' He who never sleeps... '

  • Problem with flush method

    Hello, I'm new in java development, and I'm french with a student English, sorry if that I say is strange is the expressions.
    I have a problem with network streams and serialization.
    I want to establish a connection between 2 apps, on 2 different computers. For the development, the tests are local (IP : 127.0.0.1)
    The problem : I send 4 bytes and I flush after, and I receive 6 bytes. To know what is transmitting on the connection, I override the OutputStream class.
    I think that the flush() method produces 2 bytes but i don't think how.
    I put you the codes follow :
    Thanks for any help.
    The sender function :
    // This function is called when the user want to send data to another user.
    // This piece of function establishing the connection between 2 users.
    public int startListeningForNFT(String senderUserName, int indexOfSender) {
          System.out.println(senderUserName + " demande à " + this.userName + " de démarrer la procédure de réception.");
          /* Cette fonction est l'interface ente le serveur et le client2,
           * elle retourne le port  et l'IP que le client2 le lui a renvoyé. */
          /* This function send an Integer which will trig a reception function in the receiver
             This function is called in a Thread. */
          try {
             this.oos.writeObject(44);
             this.oos.flush();
             System.out.println("On a bien envoyé OBJ2AskerInfos sur le port " + portToListen);
             byte b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
             b = this.ois.readByte();
             System.out.println("Byte = " + b);
          catch (IOException e) { e.printStackTrace(); }
          return Constantes.PORT_DATA;
       }The receiver function :
    public class ClientClient implements WindowClient {
       // This 3 attributes are initalized correctly.
       private Socket comSocket;
       private String comPort;
       private String userName;
       public ClientClient() {
          try {
          comSocket = new Socket(ipToJoin, Integer.parseInt(comPort));
          oos = new ObjectOutputStream(new DebugOutputStream(comSocket.getOutputStream()));
          ois = new ObjectInputStream(comSocket.getInputStream());
          oos.writeObject(userName);
          oos.flush();
          ThreadInputListener til = new ThreadInputListener();
          til.start();
          catch (UnknownHostException e) { e.printStackTrace(); }
          catch (ClassNotFoundException e) { e.printStackTrace(); }
          catch (IOException e) {
             e.printStackTrace();
             JOptionPane.showMessageDialog(null, ("Auncun serveur n'a été trouvé sur l'adresse indiquée :\n" + ipToJoin), "Erreur", JOptionPane.ERROR_MESSAGE);
       public class ThreadInputListener extends Thread {
          @SuppressWarnings("unchecked")
          public void run() {
             try {
                while(true) {
                   Object receivedObject = ois.readObject();
                   // Si l'objet reçu est un OBJ2InfosOnAsker => Renvoyer le port.
                   // If received Object is an integer
                   if(receivedObject instanceof Integer) {
                      System.out.println(userName +" a bien reçu l'objet OBJ2InfosOnAsker...");
                      System.out.println(userName +" a bien reçu int." + receivedObject);
                      System.out.println("On lance les 4 int :");
                      // Send 4 bytes to the sender (control bytes, just for solve the problem)
                      oos.writeByte(7);
                      oos.writeByte(8);
                      oos.writeByte(9);
                      oos.writeByte(10);
                      oos.flush();
                      System.out.println("...et a bien envoyé le port");
             catch (IOException e) {
                // ArrayList<HostClient> temp = new ArrayList<HostClient>();
                // temp.add(new HostFictiveClient(userName));
                // fenetreprincipale.updateClientList(temp);
                fenetreprincipale.addDiscution("Vous avez été déconnecté du serveur.");
             catch (ClassNotFoundException e) { e.printStackTrace(); }
       }The override function of OutputStream :
       public class DebugOutputStream extends OutputStream {
          private OutputStream os;
          public DebugOutputStream(OutputStream os) {
             super();
             this.os = os;
          @Override
          public void write(int b) throws IOException {
             System.out.println("ClientClient envoie " + b + " soit " + ((char)b));
             os.write(b);
    }The sender function says :
    Host demande à User1 de démarrer la procédure de réception.
    On a bien envoyé OBJ2AskerInfos sur le port 3001
    Byte = 4
    Byte = 0
    Byte = 7
    Byte = 8
    Byte = 9And the receiver function says :
    User1 a bien reçu l'objet OBJ2InfosOnAsker...
    User1 a bien reçu int.44
    On lance les 7 int :
    ClientCLient envoie 119 soit w       //
    ClientCLient envoie 4 soit          // Both of this lines are stranges
    ClientCLient envoie 7 soit
    ClientCLient envoie 8 soit
    ClientCLient envoie 9 soit      
    ClientCLient envoie 10 soit
    ...et a bien envoyé le port

    Minimus wrote:
    Ok, but this layer has maid just to print in the eclipse console the bytes written on the stream, With or without this function, the flush() operation generate 2 bytes, I don't know why.
    When I want to send manually the byte '7', the result of both lines :
       oos.writeByte(7);
    oos.flush();is that my writeByte and my flush send 3 bytes :
    Byte val = 119 charcode = w
    Byte val = 1 charcode =
    Byte val = 7 charcode =
    Only the 'Byte val = 7 charcode = ' line is good.
    Why the flush generate 2 unknown bytes at this code position ?Actually, it's (might be) writing more than two bytes. Run this:
    public class OOSTest {
       public static void main(String[] args) throws Throwable {
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ObjectOutputStream oos = new ObjectOutputStream(baos);
          oos.writeByte(7);
          oos.close();
          byte[] bytes = baos.toByteArray();
          System.out.println(Arrays.toString(bytes));
          //prints "[-84, -19, 0, 5, 119, 1, 7]"
    }The explanation is in the Javadoc for ObjectOutputStream:
    Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. OOSs should only be used when the OIS is being used properly on the other end. If you don't want this header, use a DataOutputStream. Is there an actual problem or are you just confused about the extra bytes? If there is a problem in reading, my guess is that you're somehow not reading from your OIS symmetrically with your OOS. Can you post a complete, compilable example that demonstrates the behaviour? There's obviously an issue somewhere, I just haven't spotted it yet.
    If there wasn't an actual problem in reading, well: there's your explanation.
    Edited by: endasil on 26-Oct-2009 10:55 AM

  • Having Problems with removing an addEventListener

    Greetings Adobe community,
    Im currently having a problem with my flash assignment,
    I have a:   this.addEventListener(Event.ENTER_FRAME, onPanSpace);
    who is causing errors when I go to the next frame:
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
              at Confabulation_fla::mc2_3/onPanSpace()[Confabulation_fla.mc2_3::frame1:13]
    I would like to remove this addEventListener when I go to the next frame(which is by clicking on a door) but to be honest, I have no clue how.
    So I ask you "How do I remove this addEventListener on my next frame?"
    Kind Regards
    Notnao

    function addTheListeners():void {
         addEventListener(Event.ENTER_FRAME, onPanSpace);
         addEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
    var snelheidNum:Number = 0.5;
    var snelheid:Number = 0;
    var MouseIsLinks:Boolean;
    function onPanSpace(e:Event):void
              var afstand:Number = Math.round(this.x - this.bg1.x);
              var percentage:Number = Math.floor((100 * afstand) / (this.bg1.width - root.stage.stageWidth));
              snelheid = -((root.stage.mouseX - (root.stage.stageWidth / 2))/110)/snelheidNum;
              if(root.stage.mouseX < (root.stage.stageWidth / 2)) { MouseIsLinks = true }
              if(root.stage.mouseX > (root.stage.stageWidth / 2)) { MouseIsLinks = false }
              if( (percentage < (1 - 100) && MouseIsLinks) || (percentage > (80 - 100) && !MouseIsLinks)) {snelheid = 0;}
              this.bg1.x += (snelheid / 1);
    function cleanUp(e:Event):void {
         removeEventListener(Event.ENTER_FRAME, onPanSpace);
         removeEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
    //this.addEventListener(Event.ENTER_FRAME, onPanSpace);
    stop();
    This is what I got now, It removes the addeventListeners and I have no problems at the next frame but now my first frame doesnt have the onPanspace effect.

  • Serious problems with paint method, need major help

    I've got a mjor problem with displaying a BufferedImage Object. My program takes in an image, i call a method on it which creates an ImageObject, imgObj, which contains the following values:
    Image width, called width
    Image height, called height,
    array of 8 bit integers for the ARGB value of each pixel, called int [] imgCol
    I've managed to create a Buffered Image of the form:
    //make a buffered image ready to take the array of pixels
    bufferedImage = new BufferedImage( imgObj.width, imgObj.height, BufferedImage.TYPE_INT_ARGB);
    Then I set the ARGB values in the BufferedImage, by specifying the integer array of pixels, imgCol:
    //set the values in the buffered image using buffered image method
    bufferedImage.setRGB( 0, 0, imgObj.width, imgObj.height, imgObj.imgCol, 0, imgObj.width);
    Then I try to paint it, callling repaint() in the same method as the code above.
    Now when I try the following stuff I get a Null Pointer Exception:
    public void paint(Graphics g){
         paintImage(g);
    public void paintImage(Graphics g){
         Graphics2D ImageGraphic2 = (Graphics2D)g;
         // Draws the buffered image to the screen.
         ImageGraphic2.drawImage(bufferedImage, 0, 0, this);
    Can anyone help me in fixing this problem?

    Here's the full stack trace, can't make heads or tails of what it's about though
    Full thread dump Java HotSpot(TM) Client VM (1.4.1_01-b01 mixed mode):
    "AWT-EventQueue-0" prio=7 tid=0x0ADAB440 nid=0xb38 in Object.wait() [ef5f000..e
    5fd8c]
    at java.lang.Object.wait(Native Method)
    - waiting on <02F78010> (a java.awt.EventQueue)
    at java.lang.Object.wait(Object.java:426)
    at java.awt.EventQueue.getNextEvent(EventQueue.java:333)
    - locked <02F78010> (a java.awt.EventQueue)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchT
    read.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThr
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    "DestroyJavaVM" prio=5 tid=0x00034DB8 nid=0x5dc waiting on condition [0..7fadc]
    "Java2D Disposer" daemon prio=10 tid=0x0AD4D1F0 nid=0x218 in Object.wait() [ef9
    000..ef9fd8c]
    at java.lang.Object.wait(Native Method)
    - waiting on <02FE9938> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111)
    - locked <02FE9938> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127)
    at sun.java2d.Disposer.run(Disposer.java:97)
    at java.lang.Thread.run(Thread.java:536)
    "AWT-Windows" daemon prio=7 tid=0x0ACB1528 nid=0x63c runnable [aeff000..aeffd8c
    at sun.awt.windows.WToolkit.eventLoop(Native Method)
    at sun.awt.windows.WToolkit.run(WToolkit.java:253)
    at java.lang.Thread.run(Thread.java:536)
    "AWT-Shutdown" prio=5 tid=0x0ACB1158 nid=0x480 in Object.wait() [aebf000..aebfd
    c]
    at java.lang.Object.wait(Native Method)
    - waiting on <02FA4990> (a java.lang.Object)
    at java.lang.Object.wait(Object.java:426)
    at sun.awt.AWTAutoShutdown.run(AWTAutoShutdown.java:259)
    - locked <02FA4990> (a java.lang.Object)
    at java.lang.Thread.run(Thread.java:536)
    "Signal Dispatcher" daemon prio=10 tid=0x009E8350 nid=0x788 waiting on conditio
    [0..0]
    "Finalizer" daemon prio=9 tid=0x0003E978 nid=0x3f0 in Object.wait() [ab1f000..a
    1fd8c]
    at java.lang.Object.wait(Native Method)
    - waiting on <02F699B0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111)
    - locked <02F699B0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)
    "Reference Handler" daemon prio=10 tid=0x0003D548 nid=0x7a4 in Object.wait() [a
    df000..aadfd8c]
    at java.lang.Object.wait(Native Method)
    - waiting on <02F69A18> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:426)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:113)
    - locked <02F69A18> (a java.lang.ref.Reference$Lock)
    "VM Thread" prio=5 tid=0x009E52C0 nid=0x974 runnable
    "VM Periodic Task Thread" prio=10 tid=0x009E7040 nid=0x4e4 waiting on condition

  • Problem with removing spaces

    Hi,
    I have a problem with spaces. There are constantly two spaces open named Safari. I cannot remove them. See enclosed image. Any ideas how to do it?

    Further research shows that the spaces are indeed there when I view the page source; however, the spaces are not being rendered.
    I removed the css style sheet that was being applied to the shuttle and it made no difference.

  • Problem with getPrimaryKeys method in DatabaseMetaData

    I'm using the above mentioned method to get primary keys from a DB2 database. I estimate that 95% of the time it performs as expected, but there are 7 tables in my database, that as far as I can see, are no different to any others and it fails to work with these. Looking at the tables in the DB2 control centre shows them all having keys, no different to any of the other tables. Also of note is that the tables it fails on are next to each other, it fails on tables 68 and 69, 135 and 136 and 200,201 and 202. Just wondering if anyone else has seen this problem before and if they found any solutions for it?
    Just ran through the program again and it's failed on a completely different set of tables, they're all sequential as well, could this be a problem with my connection to the db?
    Edited by: jnaish on Aug 14, 2008 7:38 AM

    post the ddl and code i guess
    i doubt this is related to your connection
    Also of note is that the tables it fails on are next to each other, i can't imagine that would be a problem, but sounds like it'd be easy for you to prove your theory with a simple test

Maybe you are looking for

  • Weird behavior by APD

    Hi Guru's I am observing very weird behavior in one of the process chain at APD step.APD step is getting failed due to lack of logs and due to this chain status is changed to failure in work-load automation screen.But without my intervention this ste

  • International - Date

    Date fields in the reports are not displaying as System Date Format. Pulled the date fields and set the format as System Default Shrt format. Ran the report and display the date in System Date format BUT TIME is getting displayed. How to suppress the

  • Replication entry

    I am on page 282 of the of the ldap admin guide for ldap Directory Server 5.0 sp1. I am numder two, which is discussing creating and entry for the supplier bind DN. I do not understand how I to go about doing this. Some help would be much appreciated

  • Problem in creating 0027 infotype record in background

    Hi Experts, I am facing the problem in creating 27(Costs distribution) infotype record in back ground. Whenever there is a change in position of the employee or when we hire a new employee (Through PA40) i have to ctreate 0027 infotype record in back

  • Mapviewer:GetCapabilities VERSION=1.1.1   Error 500--Internal Server Error

    Hi: i have configured the WMS secition in the mapviewer configuration file.(mapviewer:mapviewer1112,Oracle WebLogic Server 11g Rel 1 (10.3.3) ) It is correct to GetCapabilities works for: "http://172.17.1.128:8888/mapviewer/wms?REQUEST=GetCapabilitie