0

I have a class Kostka , that has its own width (w), height (h), x and y positions for drawing it later on a JPanel using this method

void maluj(Graphics g) {
    g.drawRect(x, y, w, h);
}

Now I need to make more of them and add them in ArrayList .. then call the maluj(g) method for each of the Kostka object stored in the ArrayList


So far I've managed to make a method that stores the Kostka objects in ArrayList, but I dont know how to call their methods

class MyPanel extends JPanel {
    ArrayList kos = new ArrayList(5);

    void addKostka() {
        kos.add(new Kostka(20,20,20,20));
    }

    public void paintComponent (Graphics g) {
        super.paintComponent(g);
    }
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user2347921
  • 83
  • 1
  • 5
  • 12
  • 1
    First off, you should be using Generics. Second, you should read the tutorial on using Collections and Lists if you don't understand how they work - http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html – Brian Roach Jun 12 '13 at 14:12

2 Answers2

3

Invoking Methods

That's done the normal way:

// where kostka is an instance of the Kostka type
kostka.whateverMethodYouWant();

However, the way to retrieve the kostka from your list will depend on how you declared the list.

Using the Good Ol' Way (Pre-Java 1.5 Style)

// where index is the position of the the element you want in the list
Kostka kostka = (Kotska) kos.get(index);

Using Generics (The Better Way)

ArrayList<Kostka> kos = new ArrayList<Kostka>(5);

Kostka kostka = kos.get(index);
haylem
  • 22,460
  • 3
  • 67
  • 96
2

You can perform a "cast" in order to retrieve the Kostka elements of the ArrayList:

for (int i = 0; i < kos.size(); i++) {
    Kostka kostka = (Kotska)kos.get(i);
    kostka.maluj(g);
}

If you are using a version of Java which supports Generics, the cast is unnecessary. You can do:

ArrayList<Kostka> kos = new ArrayList<Kostka>(5);

for (int i = 0; i < kos.size(); i++) {
    Kostka kostka = kos.get(i);
    kostka.maluj(g);
}
Piovezan
  • 3,215
  • 1
  • 28
  • 45