File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Help w/ controlling my dots. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help w/ controlling my dots." Watch "Help w/ controlling my dots." New topic

Help w/ controlling my dots.

Julie Mendez

Joined: Oct 04, 2004
Posts: 7
I am still having trouble handling me dots. They will not run in my loop i can get only 4 dots to appear. Is there someone there can help me out. THe bottom is my program


import javax.swing.*;
import java.awt.*;
import java.util.*;

public class RandomWalk extends JApplet

public void paint( Graphics g )
super.paint( g );

int x=160, y=160;
int side = 6;
int distance;

//random number generated
Random randomNumbers = new Random();

// stores each random integer generated
int move = -1;

//to draw square grid.
for(int i = 10; i<310; i += 30)
for(int j = 10; j<310; j += 30)
g.drawRect(i, j, 30,30);

//set position
g.fillOval ( x-3, y-3, side, side);

for ( int z = 0; z < 100; z++ )

move = 0 + randomNumbers.nextInt( 3 );

switch (move)

case 0: //north

g.fillOval ( x-3, y-30, side, side);

case 1: //south

g.fillOval ( x-3, y+30, side, side);

case 2: //east

g.fillOval ( x-30, y-3, side, side);

case 3: //west

g.fillOval ( x+30, y+3, side, side);

} //switch statement

Thread.sleep( 100 );
catch (InterruptedException ie)


distance = ( Math.abs( x - 160 ) + Math.abs( y - 160 ) ) / 30;

JOptionPane.showMessageDialog(null,"The ant traveled around the block " + distance + " times.");

} // paint method
} // RandomWalk
any help would be greatly appericated.

<b><i>To err is human but to really mess up the things you need a computer </b></i>
Richard Bradford
Ranch Hand

Joined: Apr 20, 2004
Posts: 48
Your program is actually drawing more than the 4 dots its just that they are on top each other as you are repeatedly drawing at the same locations.
I think what you are trying to do in your case statement is move x and y positions but are instead just using the same offsets.

Instead of g.fillOval( x-3, y+30, side, side );
try g.fillOval( x-=3, y+=30, side, side );

-= & += will decrement and increment the values accordingly.

Hope this helps.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I would suggest a slightly different modification to your code. Instead of

Personally, I think this is clearer than Richard's suggestion in that you are not trying to do so many things in a single line of code.



Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Help w/ controlling my dots.
jQuery in Action, 3rd edition