爪哇 - 一个对象,它是在ArrayList的调用方法 [英] Java - calling methods of an object that is in ArrayList

查看:104
本文介绍了爪哇 - 一个对象,它是在ArrayList的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个类的 Kostka ,有它自己的宽度(W),高度(h),x和y位置,使用这种方法后溺水它放在一个JPanel

 无效maluj(图形G){
    g.drawRect(X,Y​​,W,H);
}

现在我需要让更多的人,并在ArrayList中添加这些..然后调用 maluj(G)方法为每个 Kostka 存储在ArrayList对象


到目前为止,我设法使存储的Kostka的ArrayList中的对象,的方法,但我不知道该怎么称呼他们的方法

 类MyPanel继承JPanel {
ArrayList的科斯=新的ArrayList(5);无效addKostka(){
    kos.add(新Kostka(20,20,20,20));
}公共无效的paintComponent(图形G){
    super.paintComponent方法(G);
}}


解决方案

调用方法

这样做了正常的方式:

  //其中kostka是Kostka类型的实例
kostka.whateverMethodYouWant();

然而,检索方式 kostka 从你的列表将取决于你如何申报清单。

使用好醇'的方式(pre-Java 1.5的风格)

  //其中指数是您在列表中选择所需的元素的位置
Kostka kostka =(Kotska)kos.get(指数);

使用泛型(更好的方式)

 的ArrayList< Kostka>科斯=新的ArrayList< Kostka>(5);Kostka kostka = kos.get(指数);

So i have a class Kostka , that has its own width (w), height (h), x and y positions for drawning 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);

这篇关于爪哇 - 一个对象,它是在ArrayList的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆