eyoung
eyoung

Reputation: 59

Calling multiple objects with a method in Java

I'm trying to create a calendar using Java GUI and I want to create a method to create the cells of each date. Is there any way to create a method to create a bunch of JTextAreas without manually creating each individual cell?

Creating a cell one by one I do:

public void createCell() {
    cell1 = new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS);
}

Upvotes: 0

Views: 310

Answers (1)

HenriqueMS
HenriqueMS

Reputation: 3974

You have many ways of doing that one possibility would be to create a List inside the method with the assistance of a for loop and make the method return it for you to use somewhere else.

public List<JTextArea> createMultipleCells(int numOfCells) {

         List<JTextArea> cells = new LinkedList<JTextArea>();

          for(int i = 0; i < numOfCells; i++){
            cells.add(new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS));
          }

         return cells;
    }

Same thing with an array:

public JTextArea[] createMultipleCells(int numOfCells) {

             JTextArea[] cells = new JTextArea[numOfCells];

              for(int i = 0; i < numOfCells; i++){
                cells[i] = new JTextArea(CELL_DIMENSIONS, CELL_DIMENSIONS);
              }

             return cells;
        }

Upvotes: 2

Related Questions