Results 1 to 17 of 17
  1. #1
    Grimmjow is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Question Drawing multiple instances of one class with an array

    I have been tryng to draw two objects from the same class on a JFrame for about 5 hours now:confused:, but the last object created overrides the others.

    For example I want to paint two objects from the class ball on one JFrame. I need to do this in an array, I have tried this with arrayLists and normal arrays from example codes but nothing seems to work. could anyone write me a simple piece of code or give me some tips please?

    thank you,
    Grimmjow

  2. #2
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by Grimmjow View Post
    I have been tryng to draw two objects from the same class on a JFrame for about 5 hours now:confused:, but the last object created overrides the others.
    It's hard to know just what you're doing wrong based on description without code.

    For example I want to paint two objects from the class ball on one JFrame. I need to do this in an array, I have tried this with arrayLists and normal arrays from example codes but nothing seems to work. could anyone write me a simple piece of code or give me some tips please?
    There are many examples of doing this sort of thing on the forum, but before anyone invests a bunch of time re-creating code that's already out there, why not better define just what is tripping you up. I suggest that you show us a small program that's compilable, that tries to do what you are attempting here, but in a very small program that doesn't do anything else, and this way we can know exactly what the current problems are and what you need work on.

    Suerte amigo.

    edit: oh, if you do post code, please don't forget to use code tags. They'll allow your code to maintain its format and thus (hopefully) be readable. The more readable your code, the greater the chance someone here will take the time to read it. Just place the tags:

    [code]

    and

    [/code]

    around your code.

  3. #3
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    6

    Default

    Custom Painting Approaches shows how to draw multiple "colored rectangles" on a panel. The concept for painting multiple balls will be the same.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,305
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by curmudgeon View Post
    Java Code:
    and
    How did you manage to avoid the 'working' of those tags?

    kind regards,

    Jos

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    Hmm...

    [code]

    and

    [/code]

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    Yup, same way as on the Sun/Oracle forums. I use an opening and closing italic tag after the opening bracket of the code tag. Let's see...

    [[I][/I]code] [[I][/I]/code]

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,305
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Darryl.Burke View Post
    Yup, same way as on the Sun/Oracle forums. I use an opening and closing italic tag after the opening bracket of the code tag. Let's see...

    [[I][/I]code] [[I][/I]/code]
    But I didn't see any other tags in Curmudgeon's reply, just those code tags (I do see those italics tags in your reply #5) ... I'm afraid the forum software is playing tricks on us ;-)

    kind regards,

    Jos [code] ... [/code]
    Last edited by JosAH; 05-21-2010 at 08:39 AM.

  8. #8
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    It's black magic ;)

    Actually I use HTML code for one letter in each tag, same as for posting "bad" words on a forum.

  9. #9
    Grimmjow is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Default

    I have created some simple code to get my point clear, I have also tried some of the code given in the example "camickr" gave but it was a bit to complicated.

    Main
    Java Code:
    package testing;
    
    import java.awt.Color;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JFrame;
    
    class Main{
    static JFrame frame = new JFrame();
    final static List<Rect> rectangles = new ArrayList<Rect>();
    final static int count = 0;
    
    public static void main(String[] args){
        Threads fps = new Threads();
        Rect r1 = new Rect(100, 100, 100, 100, Color.red);
        Rect r2 = new Rect(300, 100, 100, 100, Color.blue);
        
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0, 0, 800, 600);
        frame.getContentPane().add(fps);
        frame.setVisible(true);
        frame.setLayout(null);
        }
    }
    Rect:
    Java Code:
    package testing;
    
    import java.awt.Color;
    import java.awt.Graphics;
    
    public class Rect {
        static int x;
        static int y;
        static int height;
        static int width;
        static Color color;
        Rect(int x, int y, int width, int height, Color color){
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.color = color;
        }
    
        public static void draw(Graphics g){
            g.setColor(color);
            g.fillRect(x, y, width, height);
        }
    }
    Threads:
    Java Code:
    package testing;
    
    import java.awt.Graphics;
    import javax.swing.JComponent;
    
    public class Threads extends JComponent {
        Threads(){
        Thread t = new Thread(new Runnable() {
        public void run() {
            while(true) {
                repaint();
                Rect.y += 5;
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException ex) {
                        System.out.println("InterruptedException encountered");
                    }
            }
        }
        });
        t.start();
    }
    
        @Override
        public void paintComponent(Graphics g){
            Rect.draw(g);
        }
    }
    The code I gave above works, the only thing is he only displays r2 and i want to display r1 and r2 at the same time using an array or arraylist. I allready created an empty arraylist and tried tons of things to get it working. nothing works though. Could anyone help me on this?

    Regards,
    Grimmjow

  10. #10
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Number 1 problem: get rid of all the statics in Rect. ALL of them. They are going to completely mess your code up, and prevent you from having multiple Rect objects with independent behavior.

  11. #11
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    1) Create an ArrayList<Rect> in your JComponent, give it an addRect(Rect rect) method that will allow you to be able to add Rect objects to the JComponent, and in this method place the Rect into the list.

    2) In your animation routine (which should be a Swing Timer, by the way), iterate through the list, changing the x and y position of the Rect objects in the list.

    3) Then call repaint() on the JComponent when done.

    4) In the paintComponent method, iterate through the list, painting the individual Rect objects in the loop.

    For instance:
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    
    class GrimMain {
      static JFrame frame = new JFrame();
      //final static List<Rect> rectangles = new ArrayList<Rect>();
      //final static int count = 0;
    
      public static void main(String[] args) {
        DrawingComponent fps = new DrawingComponent();
        Rect r1 = new Rect(100, 100, 100, 100, Color.red);
        Rect r2 = new Rect(300, 100, 100, 100, Color.blue);
        
        fps.addRect(r1);
        fps.addRect(r2);
        
        fps.animate();
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fps.setPreferredSize(new Dimension(800, 600));
        frame.getContentPane().add(fps);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    }
    
    class Rect {
      int x;
      int y;
      int height;
      int width;
      Color color;
      Rect(int x, int y, int width, int height, Color color) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.color = color;
      }
    
      public void draw(Graphics g) {
        g.setColor(color);
        g.fillRect(x, y, width, height);
      }
    
      public int getY() {
        return y;
      }
      
      public int getHeight() {
        return height;
      }
      
      public void setY(int y) {
        this.y = y;
      }
    }
    
    class DrawingComponent extends JComponent {
      private static final int ANIMATION_DELAY = 10;
      private List<Rect> rectList = new ArrayList<Rect>();
      private int deltaY = 2;
      
      DrawingComponent() {
      }
      
      public void animate() {
        new Timer(ANIMATION_DELAY, new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            for (Rect rect : rectList) {
              int y = rect.getY();
              if (y + rect.getHeight() >= getHeight()) {
                deltaY = -Math.abs(deltaY);
              }
              else if (y <= 0) {
                deltaY = Math.abs(deltaY);
              }
              
              rect.setY(y + deltaY);
            }
            repaint();
          }
        }).start();
      }
    
      public void addRect(Rect rect) {
        rectList.add(rect);
      }
    
      @Override
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Rect rect : rectList) {
          rect.draw(g);
        }
      }
    }
    Last edited by curmudgeon; 05-21-2010 at 03:46 PM.

  12. #12
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Also, you should understand why static is messing you up. When you deal with static variables, you need to know that the variable is associated with the class not with an object of the class. For instance, your Rect class has all static variables, and so since there is only one Rect class, no matter how many Rect objects you create, there will only be one copy of those static class fields, and so you can only draw one Rect image.

  13. #13
    Grimmjow is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Default

    Wow thanks a lot so far! I finally managed to display the two rects from the same class:)


    1. Theres only one thing I dont really understand.

    Java Code:
              if (y + rect.getHeight() >= getHeight()) {
                deltaY = -Math.abs(deltaY);
              }
              else if (y <= 0) {
                deltaY = Math.abs(deltaY);
              }
    2. I'd really like to use a thread and not a timer, is that doable?
    3. Is there an easier way to move the rects seppartly?

    Regards,
    Grimmjow
    Last edited by Grimmjow; 05-21-2010 at 04:34 PM.

  14. #14
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    6

    Default

    2. I'd really like to use a thread and not a timer, is that doable?
    The proper way to do this is to use a Swing Timer, that why it was suggested.

  15. #15
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    Quote Originally Posted by Grimmjow View Post
    1. Theres only one thing I dont really understand.

    Java Code:
              if (y + rect.getHeight() >= getHeight()) {
                deltaY = -Math.abs(deltaY);
              }
              else if (y <= 0) {
                deltaY = Math.abs(deltaY);
              }
    Your code adds a constant value (5) to y, but keeps adding this value regardless of where the rectangle is on the screen, so that the rectangle is allowed to continue happily off the screen and on to oblivion.

    My code allows the rectangles to bounce. The first if block checks to see if the rectangle's y location plus the height is equal to or greater than the height of the JComponent that is displaying them. If so, it changes the value of the number added to the rectangle's y field to be a negative number so that the rectangle will move up (will have a value subtracted from its y field). Conversely, if the rectangle is at or less than 0, the top border of the screen, the deltaY, the number added to y, will be made positive so that the rectangle will move down.

    2. I'd really like to use a thread and not a timer, is that doable?
    Yes, it's doable, but it's easier to use Timers since you know that all code contained will be called on the Swing main thread, the EDT.

    3. Is there an easier way to move the rects seppartly?
    Yes, but you'll need to make your movement code more complex. Alternatively, you could give the rectangles some intelligence and let each one handle its own movement.

  16. #16
    Grimmjow is offline Member
    Join Date
    May 2010
    Posts
    12
    Rep Power
    0

    Default

    Finally I am done marking this thread solved, your code made writing my code a lot easier.

    thanks again!

    Regards,
    Grimmjow

  17. #17
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    You're quite welcome, and congrats on moving forward. For better animation code, though be sure to check camickr's blog.

Similar Threads

  1. Array of instances using Math.random()
    By xgi1008 in forum New To Java
    Replies: 16
    Last Post: 01-25-2011, 11:10 PM
  2. Problem calling multiple instances of a class
    By virex in forum New To Java
    Replies: 1
    Last Post: 03-02-2010, 03:03 PM
  3. approx. 1000 instances of class?
    By artemff in forum CLDC and MIDP
    Replies: 0
    Last Post: 01-01-2010, 07:57 PM
  4. Class Instances stored in an ArrayList
    By Ersk in forum New To Java
    Replies: 4
    Last Post: 12-12-2009, 04:13 PM
  5. Problem with class instances
    By sdwinder in forum New To Java
    Replies: 7
    Last Post: 10-21-2009, 01:25 AM

Tags for this Thread

Posting Permissions

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