How to Make Java Objects Repeat
In the Java programming language, advanced data types -- comprised of other advanced data types and primitive data types -- are defined in classes. When you create an instance of that class, it is referred to as an object. Objects can be anything from a string of characters to a graphic user interface component. In some cases, you may need to create multiple instances of a java class repetitively. Java's For loop allows you to create many copies of an object with very little code.
Instructions
-
-
1
Define an array of the object type that you want to create. Make it large enough to hold all of the objects that you want to make. For example, if you wanted to create 14 JButton objects, you would use the following code:
JButton buttons[ ] = new JButton[14];
-
2
Create a new For loop that traverses all of the objects in the array. Use the following code, replacing "buttons" with the name of your array:
for(int i = 0; i < buttons.length; i++){
}
-
-
3
Create a new copy of your object inside of the loop and assign it to the current space in the object array. For example, the following code creates a new JButton and assigns it to the buttons array:
buttons[i] = new JButton();
-
4
Make any other changes to the object within the For loop's brackets. For example, the following code would change the label of all of the buttons to "Hello World:"
buttons[i].setText("Hello World:");
-
1
Tips & Warnings
Access the individual copies of an object by calling the array and the number of the object that you want to access. For example, you could access the fifth button with "buttons[4]."