Results 1 to 13 of 13
  1. #1
    patcc2 is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default Multiple objects in a class help please

    Im not entirely sure if this is the right section of the forum to be in but i'll ask my question anyway.

    I just started learning java and well object oriented code in general iv'e coded in languages before real basic stuff but never a object oriented program. I understand the basic concept of something like

    Java Code:
    Runner Test = new Runner(10,30);
    To create a new object in the class Runner called Test with parameters filled in of 10 and 30.

    However, how do i create multiple objects in my code by something such as a button press with a undefined amount of objects possible to be created. In my current situation i'm making a real simple game that will have the player press space to create a bullet. My issue being i can't use the above code to create a bullet object since if the player presses space more then twice the Test bullet will already have been created and i'll be writing over the first bullet made.

    Java Code:
    	public void fireBullet(){
    		fireBlocks Bullet =new fireBlocks(x,y,"Images/Bullet.GIF");
    	}
    This is my method to create a bullet but i know it's wrong obviously.

    I have a guess that this will involve arrays or arraylists but i don't know how to use arrays in classes and I've never used a arraylist before all i know about it is it's a array with infinite parameters.

    Any help would be nice thank you.

  2. #2
    quafflepunch is offline Member
    Join Date
    Jan 2011
    Location
    Canada
    Posts
    6
    Rep Power
    0

    Default

    you need an array of your object

    Java Code:
    public void fireBullet(){
    		fireBlocks[] Bullet =new fireBlocks[];
    	}
    
    //then for each bullet do
    
    bullet[i]= new fireBlocks("Images/Bullet.GIF");
    then everytime you press space increase the limit of the array

  3. #3
    patcc2 is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default

    are you sure thats the only way to do it i feel like an arraylist would make this easier?

    also if i have a class mainBlocks that has code that builds two classes of coloredBlocks called p1 and p2... then inside of the coloredBlocks class i have the code to create bullets... Inside the main class if i want to call on blocks would it be something like p1.Bullet[i] and p2.Bullet[i] or would the code be looking for a array inside of the coloredBlocks class called Bullet?
    Last edited by patcc2; 01-05-2011 at 02:55 AM. Reason: forgot to ask something

  4. #4
    quafflepunch is offline Member
    Join Date
    Jan 2011
    Location
    Canada
    Posts
    6
    Rep Power
    0

    Default

    can you post your code so i can see what you mean?

  5. #5
    patcc2 is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    //main class
    
    public class BlockMovement extends JFrame implements KeyListener {
    
    	int keyThatsPressed,spaceHeld,enterHeld;
    	boolean u,d,l,r,space,enter;
    	Image img;
    	Graphics graph;
    	Blocks jim= new Blocks(4,184,"Images/greenBlock.GIF");
    	Blocks fred=new Blocks(580,184,"Images/redBlock.GIF");
    
    	public BlockMovement(){
    
    		//Initalization of the JFrame
    		setTitle("hopefully bullets appear from these shapes");
    		addKeyListener(this);
    		setBounds(0,0,600,400);
    		setResizable(false);
    		setBackground(Color.BLACK);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		addKeyListener(this);
    		setVisible(true);
    		//launch();
    
    	}
    
    	/*public void launch(){
    		addKeyListener(this);
    		setBounds(0,0,600,400);
    		setResizable(false);
    		//setBackground(Color.BLACK);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		addKeyListener(this);
    		setVisible(true);
    
    
    	}*/
    
    	public void paint(Graphics g){
    
    		//double buffer the graphic
    		img=createImage(getWidth(),getHeight());
    		graph=img.getGraphics();
    
    		paintComponent(graph);
    		g.drawImage(img,0,0,this);
    		repaint();
    
    	}
    
    	public void paintComponent(Graphics g){
    
    		//update the images and then paint them in a image for the next paint call
    		update();
    		jim.draw(g);
    		fred.draw(g);
    
    	}
    
    
    	public void update(){
    
    		//Move the players up and down
    		if (u==true){
    			jim.moveUp();
    		}
    		if (d==true){
    			jim.moveDown();
    		}
    		if (l==true){
    			fred.moveDown();
    		}
    		if (r==true){
    			fred.moveUp();
    		}
    		//ensure rapid fire does not happen as well as construct bullets (construction part does not work
    		if (space==true && spaceHeld!=1){
    			spaceHeld=1;
    			jim.fireBullet();
    		}
    		if (space==false){
    			spaceHeld=0;
    		}
    		if (enter==true && enterHeld!=1){
    			enterHeld=1;
    			jim.fireBullet();
    		}
    		if (enter==false){
    			enterHeld=0;
    		}
    	}
    
    	//The key commands and their logic
    	public void keyPressed(KeyEvent e){
    		keyThatsPressed=e.getKeyCode();
    		switch(keyThatsPressed){
    			case KeyEvent.VK_UP: u=true;break;
    			case KeyEvent.VK_DOWN: d=true;break;
    			case KeyEvent.VK_LEFT: l=true;break;
    			case KeyEvent.VK_RIGHT: r=true;break;
    			case KeyEvent.VK_SPACE: space=true;break;
    			case KeyEvent.VK_ENTER: enter=true;break;
    		}
    	}
    	public void keyReleased(KeyEvent e){
    		keyThatsPressed=e.getKeyCode();
    		switch(keyThatsPressed){
    			case KeyEvent.VK_UP: u=false;break;
    			case KeyEvent.VK_DOWN: d=false;break;
    			case KeyEvent.VK_LEFT: l=false;break;
    			case KeyEvent.VK_RIGHT: r=false;break;
    			case KeyEvent.VK_SPACE: space=false;break;
    			case KeyEvent.VK_ENTER: enter=false;break;
    		}
    	}
    	public void keyTyped(KeyEvent e) {
    	}
    
    
    
    	public static void main (String[] args){
    
    	BlockMovement bob=new BlockMovement();
    
    
    	}
    
    
    
    
    }
    that is the main controller class that does the logic and the drawing. my launch code is commented out right now since I placed launched inside the init just had two different ideas left them both in for now.

    Java Code:
    import java.awt.*;
    
    public class Blocks {
    
    	int x,y,i;
    	Image img;
    
    
    
    	public Blocks(int x,int y){
    		this.x=x;
    		this.y=y;
    	}
    
    	//constructor that also sets the image for the object
    	public Blocks(int x,int y, String s){
    		this.x=x;
    		this.y=y;
    		img=Toolkit.getDefaultToolkit().getImage(s);
    	}
    
    	public void moveUp(){
    		y--;
    	}
    
    
    	public void moveDown(){
    		y++;
    	}
    
    	//places that image in the images for later
    	public void draw(Graphics g){
    		g.drawImage(img,x,y,null);
    	}
    	//will later construct infinite possible bullets not now though
    	public void fireBullet(){
    		fireBlocks Bullet =new fireBlocks(x,y,"Images/Bullet.GIF");
    		//fireBlocks[] Bullet =new fireBlocks[]();
    		//Bullet[i]=new fireBlocks(x,y,"Images/Bullet.GIF");
    	}
    
    
    }
    this is my code for the blocks aka players themselves as you can see ive commented out some different concepts for making the fireblocks class since they had errors I can not remember what right now though sorry.

    Java Code:
    import java.awt.*;
    
    public class fireBlocks {
    
    	int x,y;
    	Image img;
    
    
    	public fireBlocks(int x,int y,String s){
    		this.x=x;
    		this.y=y;
    		img=Toolkit.getDefaultToolkit().getImage(s);
    	}
    
    	public void moveForwards(){
    		x+=3;
    	}
    	public void moveBackwards(){
    		x-=3;
    	}
    	public void draw(Graphics g){
    		g.drawImage(img,x,y,null);
    	}
    }
    last my code for fire blocks as of right now clearly laking in departments its more of just a place holder so I would be able to see if a bullet was actually drawn.

  6. #6
    quafflepunch is offline Member
    Join Date
    Jan 2011
    Location
    Canada
    Posts
    6
    Rep Power
    0

    Default

    so when your declaring declare
    Java Code:
    fireBlocks[] fredBullet;
    fireBlocks[] jimBullet;
    this gives them each an array of bullets that is limitless

  7. #7
    patcc2 is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default

    ok but you still haven't told me how to access them would I do something like a for loop from 0 to the array length - 1 of both fred and jim bullets I don't understand.

    Java Code:
    fred.fireBlocks[i].draw()
    would this display the bullets if in a for loop I'm confused about that.

  8. #8
    quafflepunch is offline Member
    Join Date
    Jan 2011
    Location
    Canada
    Posts
    6
    Rep Power
    0

    Default

    oh, sorry i didn't see you're problem, so when you're declaring them in blocks, declare them once to set size, and then again to pass parameters to each instance of the array
    Java Code:
    fireBlocks[] Bullet =new fireBlocks[10]; //note not passing parameters here, and i just chose a random limit
    for (i=0;i<10;i++){
    Bullet[i]=new fireBlocks(x,y,"Images/Bullet.GIF");
    }
    to draw in your paint component use:
    Java Code:
    for (i=0;i<10;i++)
    jim.bullets[i].draw(g);
    //or 
    g.drawImage(jim.bullets[i].img,jim.bullets[i].x,jim.bullets[i].y,null)

  9. #9
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Not really sure what quafflepunch is talking about with limitless arrays (the code sample he gave that omits the size isn't valid java), but arrayLists are definitely the way to go when the number of elements is unknown.

    Plain arrays are fine if you are storing a known number of things - say 4 frame of animation. But ArrayLists are Dynamic arrays and have expansion and a lot of other features built in. For example:

    Java Code:
    //...
    ArrayList<fireBlocks> blocks = new ArrayList<fireBlocks>();
    //add some elements
    blocks.add(new fireBlocks(x,y,"Images/Bullet.GIF"));
    //iterate through entire list method 1:
    for(int i=0; i<blocks.size(); i++){
        fireBlock tmp = blocks.get(i);
        //do something with tmp
    }
    //Method 2 (fast iteration)
    for(fireBlocks fb : blocks){
        //do something with fb
        fb.doSomething();
    }
    Hope that helps!

  10. #10
    patcc2 is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default

    Thank you Quad64Bit I could have sworn I was right with the arraylist thing.

    Now then as I stated before I have never used array lists before so it would be nice if you explained some stuff.

    1.ArrayList<fireBlocks> blocks = new ArrayList<fireBlocks>();
    what does it mean when you are doing the <fireBlocks> thing I understand it would work but I would like to understand what it exactly it is doing.

    2.I have seen the for loop you used in method2 for(fireBlocks fb : blocks){ however I have only worked with a normal for loop before I am not sure how that kind of a for loop works at all again explaining would be nice.

  11. #11
    user0 is offline Senior Member
    Join Date
    Dec 2010
    Posts
    100
    Rep Power
    0

    Default

    hi - I am not sure how your game code works. But I can help you with the ArrayList question. So if you are familiar with arrays, and say you wanted to create an array of 10 Strings and an array of 10 fireBlocks, you would do it as follows:

    Java Code:
    String[] s = new String[10];
    fireBlocks[] blocks = new fireBlocks[10];
    However, the syntax for creating an ArrayList of objects is different. To create an ArrayList of String and an ArrayList of fireBlocks you would do so by calling the ArrayList constructor as follows:

    Java Code:
    ArrayList<String> s = new ArrayList<String>();
    ArrayList<fireBlocks> blocks = new ArrayList<fireBlocks>();
    ArrayList<fireBlocks> is simply a type specification, meaning you are creating an ArrayList of fireBlocks.

    Hope that helps you understand.

    Best,
    --user0--

  12. #12
    user0 is offline Senior Member
    Join Date
    Dec 2010
    Posts
    100
    Rep Power
    0

    Default

    2.I have seen the for loop you used in method2 for(fireBlocks fb : blocks){ however I have only worked with a normal for loop before I am not sure how that kind of a for loop works at all again explaining would be nice.
    Quad is using what is called a For Each loop. This type of loop can be used when you want to access each element in your list and do something with it, regardless of its position in the list (note that the for each loop does not use an index variable to move through your arraylist). As an example, lets say you have an array ints[] which has 10 integers, you would write a normal for loop as follows:

    Java Code:
    for(int i = 0, i < ints.length; i++) {
       do something with each element;
    }
    The same thing can be done with a for each loop, however, you give up the ability to know exactly where in your array a particular element resides for example. So I can rewrite the above for loop using a for each loop:

    Java Code:
    for(int x: ints) {
      do something with x;
    }
    This simply reads as: for each int element x in the array ints, do something with x.

    here is a link to some tutorials on for each loops and ArrayList API for you to refer to:

    The For-Each Loop
    ArrayList (Java 2 Platform SE v1.4.2)

    best,
    --user0--

  13. #13
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Great comments user0!
    Also to add to what he said about type specification - in java <TypeHere> is called 'Generics'. Since data structures like ArrayList normally store only Objects, in the old days before generics, it could get messy. Generics allow you to not only enforce what types of objects are stored in a collection, but also relieves you of the task of casting the stored object back into its original data type when its retrieved.

    Its also to be noted that Arrays are a language feature:
    Java Code:
    SomeType[] array = new SomeType[10];
    and that ArrayLists are objects written in java and contained in the class library that have a collection of methods you can use. Their primary feature is dynamic expansion, arbitrary maximum capacity, insertions and removals to name a few.

Similar Threads

  1. do we need multiple connection objects
    By Pacerier in forum Java Servlet
    Replies: 4
    Last Post: 11-27-2010, 06:16 PM
  2. Instantiating Multiple Graphics objects
    By theCardboardBox in forum New To Java
    Replies: 2
    Last Post: 11-25-2010, 01:26 PM
  3. Multiple Graphics Objects?
    By MrFish in forum Java 2D
    Replies: 7
    Last Post: 10-29-2010, 07:37 PM
  4. how to deserialize multiple objects in a file
    By xcallmejudasx in forum Advanced Java
    Replies: 11
    Last Post: 12-16-2008, 05:29 PM
  5. Can I store multiple objects in an array
    By lareauk in forum New To Java
    Replies: 9
    Last Post: 05-29-2008, 03:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •