简体   繁体   中英

Java - calling methods of an object that is in ArrayList

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);
    }
}

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);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM