Deal with the easy one first. In Java a memory leak is caused when an unwanted object that is no longer needed is still being referenced.
If you look at the code the object reference item
is declared inside the setup so is a local variable and will be lost when the method ends. So after setup
you have no reference to item
so you can’t call item.removeAll()
. All the ActionListeners are anonymous so no risk of memory leak there.
The only external refernence for the popup-menu menu
so a call to menu.removeAll()
will remove all JMenuItems objects so these and their ActionListenerers will be garbage collected therefore no memory leak.
Be very wary here, the draw method is executed about 60 times a second so you only want to rebuild the pop-menu if the list of available ports changes. I suggest that you need a mechanism to detect if there has been a change since the menu was updated, the actual way you do this is up to you.