Java - 调用 ArrayList 中对象的方法 [英] Java - calling methods of an object that is in ArrayList
问题描述
我有一个 Kostka 类,它有自己的宽度 (w)、高度 (h)、x 和 y 位置,以便稍后使用此方法在 JPanel 上绘制它
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);
}
现在我需要制作更多它们并将它们添加到 ArrayList .. 然后为存储在 ArrayList 中的每个 Kostka 对象调用 maluj(g)
方法
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
到目前为止,我已经设法制作了一个将 Kostka 对象存储在 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();
但是,从列表中检索 kostka
的方式将取决于您声明列表的方式.
However, the way to retrieve the kostka
from your list will depend on how you declared the list.
// where index is the position of the the element you want in the list
Kostka kostka = (Kotska) kos.get(index);
使用泛型(更好的方法)
ArrayList<Kostka> kos = new ArrayList<Kostka>(5);
Kostka kostka = kos.get(index);
这篇关于Java - 调用 ArrayList 中对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!