Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

remove the last shape  RSS feed

 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have the following problem, in this code i made an array list to get all the shapes drawn on the panel and added an undo button to remove the last shape drawn. but i tried alot and failed to remove the last item on the array list whether it is a line or rectangle or an oval. in the event handler of the undo button i am calling method clearLastShape but always get an ArrayOutOfBoundsException or the index is greater tha the size.

 
Andrea Binello
Ranch Hand
Posts: 47
4
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohamad Samy wrote:i tried alot and failed to remove the last item on the array list whether it is a line or rectangle or an oval. in the event handler of the undo button i am calling method clearLastShape but always get an ArrayOutOfBoundsException or the index is greater tha the size.

shapes.remove(shapes.size()-1);

EDIT: obviously checking before that size is > 0. I have simply pointed out the fact that just only size() is wrong. ;)
 
Randall Twede
Ranch Hand
Posts: 4683
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Rob Camick
Ranch Hand
Posts: 2787
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The paintComponent() method is for painting only.



The above logic does not belong in the paintComponent() method. This method can be called whenever Swing determines the component needs to be repainted, which means that you could be adding the "currentShape" to your ArrayList multiple times. This can then cause problems when you attempt to delete the last shape because it may have been added to the ArrayList more than once.

You should add the currentShape to the shapes ArrayList in your MouseListener code.

 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you alot for your quick response. I will move it to the event handling and check the size.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!