How to Remove Multiple Objects in Java

How to Remove Multiple Objects in Java thumbnail
Adding GUI objects to array lists can help simplify source code.

Java simplifies the tedious task of designing graphical user interfaces (GUIs) for your programs with its standard Swing library of GUI objects. However, when it comes to reorganizing the GUI at different points in the program's execution, you still have to issue separate commands for removing each object you added to the interface. You can simplify this task and remove multiple objects at once by adding sets of objects that you need to remove at the same time to an array list, then setting a for loop to remove each object in the array list.

Instructions

    • 1

      Add the line "import java.util.*" to the top of your source code.

    • 2

      Declare a new array list with the syntax "ArrayList<JComponent> windowObjects = new ArrayList<JComponent>();" where "windowObjects" is the name you will give to your array list.

    • 3

      Add the various GUI objects that you would want to remove from your program's interface at a given time by repeating the syntax "windowObjects.add(GUIObject);" for each object you want to remove at the same time. In this statement, "GUIObjects" is the name of each GUI object you are adding to the array list.

    • 4

      Remove all the objects you put in your array list with the following syntax:

      for (i = 0; i < windowObjects.size(); i++){
      Panel.remove(windowObject.get(i);
      }

      In this code segment, "i" is the name you give to an integer variable and "Panel" is the name for the JPanel object on which Java is drawing the GUI objects.

Related Searches:

References

  • Photo Credit Michael Blann/Lifesize/Getty Images

Comments

Related Ads

Featured