Results 1 to 2 of 2
- 03-18-2011, 08:53 PM #1
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
Need help on Multiple Moving Shapes
As the title says I need some help trying to figure out how to make multiple shapes that move independently of each other. I managed to make a program that can make one shape move around after spending an hour or two looking up how to use the Thread.sleep() and repaint(). Anyway here's what I got.
Any suggestions on how I would go about this with what I got so far?Java Code:import java.awt.Graphics; import javax.swing.JPanel; import java.awt.*; import java.util.Random; public class Shapes extends JPanel implements Runnable { Random myR = new Random(); int x_pos; int y_pos; int x_width; int y_height; int right=5; int left= -5; int up=-5; int down = 5; int width, height; boolean goDown, goRight; public Shapes(int x, int y, int xw, int yh) { x_pos = x; y_pos = y; x_width = xw; y_height = yh; } public void init() { } public void start () { Thread th = new Thread (this); th.start (); } @Override public void paintComponent( Graphics g ) { super.paintComponent( g ); g.setColor(Color.BLUE); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(new Color(myR.nextInt(255), myR.nextInt(255), myR.nextInt(255))); g.fillOval(x_pos, y_pos, x_width, y_height); } public void drawShape (int nx, int ny) { x_pos= nx; y_pos= ny; repaint(); } public void run () { goRight = true; goDown = true; while (true) { moveShape(); drawShape(x_pos, y_pos); repaint(); try { Thread.sleep (25); } catch (InterruptedException ex) { // do nothing } } } public void moveShape() { if(goRight) { x_pos += right; if (x_pos >= (getWidth() - x_width)) goRight = false; } else { x_pos += left; if ( x_pos <= 0) goRight = true; } if(goDown) { y_pos += down; if(y_pos >= getHeight()-y_height) goDown = false; } else { y_pos += up; if(y_pos <= 0) goDown = true; } } }Last edited by Majeh; 03-18-2011 at 10:37 PM.
- 03-19-2011, 08:54 PM #2
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
Similar Threads
-
randomly moving shapes
By marlon in forum New To JavaReplies: 3Last Post: 10-05-2012, 09:37 AM -
Moving java shapes with mouse and buttons
By Haraldjjones in forum New To JavaReplies: 1Last Post: 01-20-2011, 09:26 PM -
java shapes
By Kyle227 in forum New To JavaReplies: 7Last Post: 05-20-2010, 12:21 AM -
Inserting multiple shapes using mouseListener
By thayalan in forum Java 2DReplies: 1Last Post: 03-14-2009, 02:43 PM -
Colors and shapes.
By Torgero in forum New To JavaReplies: 14Last Post: 10-13-2008, 05:25 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks