在数组java中存储不同的对象

时间:2015-03-19 17:53:07

标签: java arrays

我需要做的是存储"障碍物"的不同对象。数组中的超类,然后执行与我有一个相同的操作。所以我需要能够绘制所有对象并使它们与球类碰撞。

所以我试图将一个对象的所有实例放在一个for循环的数组中,然后我尝试绘制它们。但如果对象存储在数组中,我无法弄清楚如何使用对象上的函数。

我试着这样做:

for(int i = 0;i<objects.length;i++){
            objects[0].paint(g);
        }

但是&#34;油漆(g)&#34;部分只是用红色突出显示,但它不起作用。

如果有人能帮助我,我真的很开心!我之前没有将对象存储在数组中,所以我有点无能为力。

我也试过像这样制作for循环:

if(i>=1 && i<15){
                Obstacle star = new StarObstacle(rand.nextInt(400),rand.nextInt(400));
                objects[i]= star;
                star.paint(g);
            }

这里他们实际上出现了,但是星星只是在屏幕上飞来飞去,所以必须始终改变x和y值。

编辑:抱歉意外添加了整个代码,而不仅仅是我需要帮助的部分。 它是Main(int x,int y){}范围

中的for循环
package com.company;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;

public class Main extends JPanel implements KeyListener {

    Ball b;
    TriangleObstacle o;
    BorderObstacle border;
    StarObstacle s;
    Player player;
    int bounceCount=0;
    Object[] objects;
    Random rand = new Random();

    Main(int width, int height) {
        //create a new black ball at the center of the screen
        b = new Ball(width*0.5f, height*0.5f, 3, 0,0,0);

        //make a border around the window
        border = new BorderObstacle(width, height);
        objects = new Object[30];


        //setup a triangle obstacle
        o = new TriangleObstacle(width*0.3f, height*0.7f, 200, 50);
        s = new StarObstacle(400,300);
        player = new Player();
        this.addKeyListener(this);
        this.setFocusable(true); //needed to make

        for(int i = 0; i < objects.length;i++){
            if(i==0){
                objects[0]= new Player();
            }

            if(i>=1 && i<15){
                objects[i]= new StarObstacle(rand.nextInt(400),rand.nextInt(400));
            }

            if(i>15){
                objects[i]= new TriangleObstacle(30,30,rand.nextInt(400),rand.nextInt(400));
            }
        }

    }

    public void update() {

        //move over all obstacles and check whether they should bounce the ball
        border.bounceBall(b);
        o.bounceBall(b);
        s.bounceBall(b);



        if(player.bounceBall(b)){
            bounceCount++;

        }


        //move ball based on speed and location
        b.move();
        player.move(); //updates my player object.


        this.repaint(); //runs the paint method on the object
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
        g.drawString("Amount of bounces on Player: " + bounceCount, 300, 100);
        b.paint(g);
        o.paint(g);
        s.paint(g);
        player.paint(g);
        border.paint(g);




    }

    public static void main(String[] args) {

        int width = 800;
        int height = 600;

        JFrame frame = new JFrame("Pinball"); //create a new window and set title on window
        frame.setSize(width, height); //set size of window
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the window to close when the cross in the corner is pressed
        Main m = new Main(width,height-22); //-22 to account for menubar height //create a new object and runs constructor for initial setup of the program
        frame.add(m); //add the content of the object to the window
        frame.setVisible(true); //make the window visible


        while (true) { //keep running a loop
            //each time the loop is run do
            m.update(); //run the update method on the object
            try {
                Thread.sleep(10); //stops this part of the program for 10 milliseconds to avoid the loop locking everything. Now the screen has time to update content etc.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode(); //gets input as keycode.
        if(code==KeyEvent.VK_RIGHT){
            player.setRight(true); //sets the movement for right to true, making it move by 5 pixels in the positive direction, for each update.
            player.setLeft(false);
        }
        if(code==KeyEvent.VK_LEFT){
            player.setLeft(true);
            player.setRight(false);
        }

    }

    @Override
    public void keyReleased(KeyEvent e) { //keyReleased setting them to false to prevent the object to keep moving.
        int code = e.getKeyCode();
        if(code==KeyEvent.VK_RIGHT){
            player.setRight(false);
        }
        if(code==KeyEvent.VK_LEFT){
            player.setLeft(false);
        }

    }
}

5 个答案:

答案 0 :(得分:0)

这:

for(int i = 0;i<objects.length;i++){
            objects[0].paint(g);
        }

由于您始终访问索引0,因此无法实现您的目标。

试试这个:

for(int i = 0;i<objects.length;i++){
            objects[i].paint(g);
        }

这允许您访问和绘制由i表示的索引上的每个对象。我不能保证这会解决问题,但它是 问题。

答案 1 :(得分:0)

您需要强制转换对象并使用正确的索引:

objects[0].paint(g);

应该是

((Observer)objects[i]).paint(g);

然而,这完全是错误的做法。请阅读java泛型。 http://docs.oracle.com/javase/tutorial/java/generics/

您应该使用List或其他具有上限通配符的集合,例如

List<? extends Observer>

这将提供类型安全。

答案 2 :(得分:0)

您需要在“Player”,“StarObstacle”,“TriangleObstacle”等类中编写自己的方法绘画(图形g)。

类似的东西:

 class TriangleObstacle extend Obstacle {
   public paint(Graphics g) {
     g.drawPolygon (...);
   }
 }

另外,避免使用Objects(Objects [])数组。更好地使用你的超类障碍阵列(障碍[] myObstacle =新障碍[30];

并且不要将Player对象放在Obstacle数组中,这是没有意义的。

在决赛中你可以:

Obstacle[] myObstacles = new Obstacle[30];
Player player = new Player();
....
for (Obstacle obstacle : myObstacles) {
  obstacle.paint(g);
}
player.paint(g);

答案 3 :(得分:0)

您必须创建一个Obstacles而不是objects的数组,在Obstacles界面中添加一个名为paint()的方法定义。然后,您必须在每个Obstacles实现中覆盖paint()方法。当你在数组的对象中调用paint方法时,它将调用相应的方法。

答案 4 :(得分:0)

您可以将对象放在列表中而不是数组吗?有点像...

List<Obstacle> someList = [however you populate your array, just populate the list instead];

for(int i = 0; i<somelist.length; i++) {
    someList.get(i).paint(g);
}