Error passing array as parameter - Java - java

A program I'm modifying is supposed to use a drawing panel to randomly move a square, starting from the center, either left or right and use an array to tally the position it moves to while the square stays on screen (the panel is 400 x 400 and the square is 10 x 10, so there are only 40 possible positions it can move to) After the square goes off screen, I have to print a histogram that shows how many times the square moved to that index (i.e if the square moved from the x coordinate of 200 to 190, index 19 would get a tally) Here is my code:
import java.awt.*;
import java.util.*;
public class RandomWalkCountSteps {
// DrawingPanel will have dimensions HEIGHT by WIDTH
public static final int HEIGHT = 100;
public static final int WIDTH = 400;
public static final int CENTER_X = WIDTH / 2;
public static final int CENTER_Y = HEIGHT / 2;
public static final int CURSOR_DIM = 10;
public static final int SLEEP_TIME = 25; // milliseconds
public static void main( String[] args ) {
DrawingPanel panel = new DrawingPanel( WIDTH, HEIGHT );
Random rand = new Random();
walkRandomly( panel, rand );
}
public static void walkRandomly( DrawingPanel panel, Random rand ) {
Graphics g = panel.getGraphics();
int[] positionCounts = new int[ WIDTH / CURSOR_DIM ];
// start in center of panel
int x = CENTER_X;
int y = CENTER_Y;
// Draw the cursor in BLACK
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
// randomly step left, right, up, or down
while ( onScreen( x, y ) ) {
panel.sleep( SLEEP_TIME );
// Show a shadow version of the cursor
g.setColor(Color.GRAY);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
if ( rand.nextBoolean() ) { // go left
x -= CURSOR_DIM;
}
else { // go right
x += CURSOR_DIM;
}
positionCounts[ x / CURSOR_DIM ]++;
histogram(positionCounts, x, y);
// draw the cursor at its new location
g.setColor(Color.BLACK);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
}
}
public static boolean onScreen( int x, int y ) {
return 0 <= x && x < WIDTH
&& 0 <= y && y < HEIGHT;
}
public static void histogram(int[] positionCounts, int x, int y) {
if (onScreen(x, y) == false) {
for (int i = 0; i < WIDTH / CURSOR_DIM; i++) {
System.out.print(i + ": ");
for (int j = 1; j <= positionCounts[i]; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
My problem was that I couldn't find a good place to initialize the array so that it wouldn't re-initialize every time I passed the x coordinate to the histogram method. Now that I thought I had it in the right place, I get this error message on both calls to histogram in the method walkRandomly "error: method histogram in class RandomWalkCountSteps cannot be applied to given types;" I'm fairly new to java and programming in general, so there's probably something I'm missing regarding arrays as parameters. Thanks in advance.

histogram takes two parameters, positionCounts of type int[] and x of type int. In walkRandomly, you call histogram twice: once with an argument positionCounts of type int[] and once with an argument x of type int. That’s why the compiler complains that the method ”cannot be applied to given types”: the method histogram(int[], int) can’t be applied to (called with) the given types, i.e., histogram(int[]) and histogram(int).
I’m not sure what you’re trying to do with this code, but I’d guess that you want remove the first call and change the second call (inside of the while loop) to histogram(positionCounts, x).
(You’ve edited your code, so my answer doesn’t make much sense.)

Related

Can't get past recursion for Sierpinki's Triangle

I just need to get this code working. I know it's not good form or very efficient but I just need it to draw the Sierpinski's Triangle, recursively. It reaches the first recursive call, but never gets past it and only draws part of the triangle. I know I'm being stupid and the answer will be obvious but I haven't coded in a long time. Thank you for any help!
import javax.swing.*;
import java.awt.*;
public class recursiveTriangle18 extends JApplet
{
private final int APPLET_WIDTH = 800;
private final int APPLET_HEIGHT = 800;
/*
//x is accross and y is down
point 1 - Right A x[0],y[0] (720,600)
point 2 - Left B x[1],y[1]
point 3 - Top C x[2],y[2]
point 4 draws back to point 1 to complete triangle
*/ private int[] xPos = {720, 80, 400, 720};
private int[] yPos = {600, 600, 40, 600};
//-----------------------------------------------------------------
// Sets up the basic applet environment.
//-----------------------------------------------------------------
public void init()
{
setBackground (Color.white);
setSize (APPLET_WIDTH, APPLET_HEIGHT);
}
//-----------------------------------------------------------------
// Draws a rocket using polygons and polylines.
//-----------------------------------------------------------------
public void paint (Graphics page)
{
page.setColor (Color.BLUE);
page.drawPolyline (xPos, yPos, xPos.length);
Triangle(xPos,yPos, 0, page);
}//end of paint
public void Triangle(int[] xPos, int[] yPos, int flag, Graphics page)
{
//Find the distance between 2 points ex. - x,y & x1,y1
int x = xPos[0];
int x1 = xPos[1];
int x2 = xPos[2];
int x3 = xPos[3];
int y = yPos[0];
int y1 = yPos[1];
int y2 = yPos[2];
int y3 = yPos[3];
double dist = Math.sqrt((x-x1)*(x-x1) + (y-y1)*(y-y1));
//find the mid points of each line segment
while (dist >= 100){
int midpointx = ((x+x1)/2);
int midpointy = ((y+y1)/2);
int midpointx1 = ((x1+x2)/2);
int midpointy1 = ((y1+y2)/2);
int midpointx2 = ((x2+x3)/2);
int midpointy2 = ((y2+y3)/2);
//make the x and y array (3 points + first point to finish triangle)
//create x,y Array using the midpoints you calculated
int [] xpoints = {midpointx2, midpointx, midpointx2};
int [] ypoints = {midpointy2,y, midpointy, midpointy2};
int [] xpoints1 = {midpointx, midpointx1, x1, midpointx};
int [] ypoints1 = {midpointy, midpointy1, y1, midpointy};
int [] xpoints2 = {midpointx1, midpointx2,x2,midpointx1};
int [] ypoints2 = {midpointy1, midpointy2,y2,midpointy1};
page.drawPolyline(xpoints1, ypoints1, xpoints1.length);
page.drawPolyline(xpoints2, ypoints2, xpoints2.length);
page.drawPolyline(xpoints, ypoints, xpoints.length);
//if the segment/distance is 300 or so, good length to stop
// Recursive calls for each section of triangle
Triangle(xpoints, ypoints, flag, page);
Triangle(xpoints2, ypoints2, flag, page); // how to get here?
Triangle(xpoints1, ypoints1, flag, page);
}
}
//end of Triangle
}
Triangle(xpoints, ypoints, flag, page);
Triangle(xpoints2, ypoints2, flag, page); // how to get here?
Every Triangle call is making another call to Triangle, so it's an infinite recursion that never returns. You need an if (stop condition) block around the recursive calls to tell it when to stop recursing.
There's also another issue:
double dist = Math.sqrt((x-x1)*(x-x1) + (y-y1)*(y-y1));
//find the mid points of each line segment
while (dist >= 100){
You never update the value of dist, so this is an infinite loop.

Java beginning if statement in for loop being skipped while others work

Back again with another problem that has stumped me completely and cannot for the life of me fix.
So I had previously posted a question about my Java game I am making for a class that with the help of #MadProgrammer was fixed...mostly. Now there is a new problem that needs a post all to it's own
Previous Post:
Rows and columns with multidimensional array java
Problem:
In the code below I have it set up to loop through the variables x and y to make rows and columns on a jPanel. Each time it loops through it should randomly mark the "x,y" location with one of the "terrains" so that later it can "paint" that location with the appropriate colored 20x20 square.
The code runs great except for one thing, it looks like it skips the very first "if statement" that marks the "terran[0]" which is "floor". When the code is ran it "paints" the other three "terrains" and not a single "floor" "terrain".
I have looked for a solution on these posts but no success:
Java if statement is skipped
If statement being skipped during execution
Java - for loops being skipped
Java if-statement being skipped
Here is a working piece of code that results in the problem at hand:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class gamePanel extends JPanel
{
public gamePanel()
{
setBounds(115,93,480,480);
}
private Random generator = new Random();
int floor = 0; //initializes the variable floor to zero for later use
int dirt = 1;
int stone = 2;
int water = 3;
int width = 24;
int height = 24;
int x, y; // my x & y variables for coordinates
int[][] coords = new int[width][height]; //my array that I want to store the coordinates for later use in painting
int[] terrain = {floor, dirt, stone, water}; //my terrain that will determine the color of the paint
public void mapGen() //what should mark/generate the JPanel
{
for(x = 0; x < width; x++)
{
for(y = 0; y < height; y++)
{
int z = generator.nextInt(20);// part of the randomization
if(z <= 10)
{
coords[x][y] = terrain[0]; //should mark the coordinates as floor
}
if(z == 11)
{
coords[x][y] = terrain[3];//should mark the coordinates as water
}
if(z >= 12 && z <= 16)
{
coords[x][y] = terrain[2];//should mark the coordinates as stone
}
if(z >= 17 && z <= 19)
{
coords[x][y] = terrain[1];//should mark the coordinates as dirt
}
coords[0][0] = terrain[0]; // sets coordinate 0,0 to floor //need to have these always be floor
coords[23][23] = terrain[0]; // sets coordinate 24,24 to floor //^^^^^^^^^^
}
}
}
#Override
public void paintComponent(Graphics g)//what will paint each 20x20 square on the grid what it is assigned
{
super.paintComponent(g);
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
mapGen();
if(coords[x][y] == terrain[floor])//should paint the floor color at marked coordinates
{
g.setColor(Color.white);
g.fillRect((x*20), (y*20), 20, 20);
}
if(coords[x][y] == terrain[dirt]);//should paint the dirt color at marked coordinates
{
g.setColor(new Color(135,102,31));
g.fillRect((x*20), (y*20), 20, 20);
}
if(coords[x][y] == terrain[stone])//should paint the stone color at marked coordinates
{
g.setColor(new Color(196,196,196));
g.fillRect((x*20),(y*20),20,20);
}
if(coords[x][y] == terrain[water])//should paint the water color at marked coordinates
{
g.setColor(new Color(85,199,237));
g.fillRect((x*20),(y*20),20,20);
}
}
}
}//end paintComponent
public static void main(String[] args)
{
gamePanel panel = new gamePanel();
JFrame frame = new JFrame();
frame.setSize(500,550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.setVisible(true);
}//end main
}// end gamePanel
Please keep in mind that I am a novice programmer and I am still learning. So anything that is not considered "basic" code please explain in detail.

randomWalk.java what am i missing (Beginner)

I have most of the code written im just having some difficulty finishing up. I am supposed to create some code that will have a square randomly walk around on the drawing board until it walks off the screen. I can get it to work a little bit but i have a feeling it's not correct. Any help will be appreciate.
Here is an example of what it is supposed to look like
Here is my code so far the problem im most concerned about is the walkingRandom method it has stars by it
public class RandomWalk {
// DrawingPanel will have dimensions DIM by DIM
public static final int DIM = 400;
// Start the random walk in the center of the screen
public static final int CENTER = DIM / 2;
// how big should the cursor appear?
public static final int CURSOR_DIM = 10;
// how long should the cursor saty in one place?
public static final int SLEEP_TIME = 5; // milliseconds
public static void main( String[] args ) {
DrawingPanel panel = new DrawingPanel( DIM, DIM );
Random rand = new Random();
walkRandomly( panel, rand );
}
/**
* Draw a random walk on the panel.
* Stop as soon as you walk off the panel.
* Each random step should go only in one
* of these directions: left, right, up, down.
* #param panel a DrawingPanel to draw the
* random walk on
* #param rand a Java Random object to be
* used to generate random steps
*/
public static void walkRandomly( DrawingPanel panel, Random rand ) {
Graphics g = panel.getGraphics();
// start in center of panel
int x = CENTER;
int y = CENTER;
// Randomly step left, right, up, or down
// until cursor goes off screen.
while ( onScreen( x, y ) ) {
// Draw the cursor in BLACK
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
// Wait a bit.
panel.sleep( SLEEP_TIME );
// Show a shadow version of the cursor
g.setColor(Color.GRAY);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
// Choose a new location for the cursor
//*********************************
if (rand.nextInt() < DIM - 300){
x--;
} else if (rand.nextInt() < DIM / 2){
x++;
} else if (rand.nextInt() < DIM - 100){
y--;
} else if (rand.nextInt() < DIM) {
y++;
}
//*********************************
// draw the cursor at its new location
g.setColor(Color.BLACK);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
}
}
/**
* determine whether (x, y) is a point on the panel.
* #param x the x-coord of the cursor
* #param y the y-coord of the cursor
* #return true if (x,y) is on the screen,
* false if (x,y) is off the screen
*/
public static boolean onScreen( int x, int y ) {
// x/y high = 400, x/y low = 0
//*********************************
return (x <= DIM && x >= 0 || y <= DIM && y >= 0);
}
}
There's a few issues with your code. You did not quite clarify in your question, but I assume that:
All directions should have the same probability of occurring
The cursor can only move "full steps" i.e. it has to move by CURSOR_DIM at a time, not less (that's what seems to be happening in your example)
The problem is mainly in the method walkRandomly, I suggest that you select the next direction as follows:
// Choose a new location for the cursor
int direction = rand.nextInt(4); //0=left, 1=right, 2=up, 3=down
if (direction == 0){
x -= CURSOR_DIM; //The step should be equal to the cursor width, not 1
} else if (direction == 1){
x += CURSOR_DIM;
} else if (direction == 2){
//you usually subtract to go up, the origin being the upper-left corner
y -= CURSOR_DIM;
} else if (direction == 3) {
y += CURSOR_DIM;
}
There's two other issues:
You are drawing the cursor in black at the beginning and at the end of the loop, this is redundant. You could remove one of them and have the same result.
In the onScreen method, x and y values equaling DIM should return false, since usually the bounds of an image/array are 0 to DIM exclusive. Also you should replace the || by an AND, because the cursor should be within the x AND y range, not OR.
return (x < DIM && x >= 0 && y < DIM && y >= 0);
Hope it helps

Maze, optimal path finding using stacks

i have a program that generates a random maze. In the maze a red dot is displayed and the red dot flashes on by each block in the maze. all the blocks in the maze are == 1 and if the red dot goes through that block, it increments ++. the red dot goes in the direction towards the lowest number, that way it wont stay in an infinite loop by a dead end. once it reaches the end, ive solved the maze.
This is where im stumped, im trying to print the red dot to find the optimal route all the way back to the beginning where it started. I used a stack class that i made to record all the y and x components of where the red dot traveled. im able to traceback every where the red dot has gone but that isnt the optimal solution.
My question is how could i print the red dot tracing back in only the optimal path. My idea of solving this would be to check and see if the coordinates of a stack where visited before, if so..find the last case where it was visited and print the red dot up until that point. that way itll never deal with the dead ends it traveled.
the method solve() is what contains the traceback and solving technique for the red dot to travel through the maze and back.
Im not the greatest programmer and im still learning how to use stacks, ive been stumped for hours and dont know how to approach this. Please be kind and explain how you would do it using the stack i made. Thank you
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import javax.swing.*;
public class mazedfs extends JFrame implements KeyListener
{
/* default values: */
private static int bh = 16; // height of a graphical block
private static int bw = 16; // width of a graphical block
private int mh = 41; // height and width of maze
private int mw = 51;
private int ah, aw; // height and width of graphical maze
private int yoff = 40; // init y-cord of maze
private Graphics g;
private int dtime = 40; // 40 ms delay time
byte[][] M; // the array for the maze
public static final int SOUTH = 0;
public static final int EAST = 1;
public static final int NORTH = 2;
public static final int WEST = 3;
public static boolean showvalue = true; // affects drawblock
// args determine block size, maze height, and maze width
public mazedfs(int bh0, int mh0, int mw0)
{
bh = bw = bh0; mh = mh0; mw = mw0;
ah = bh*mh;
aw = bw*mw;
M = new byte[mh][mw]; // initialize maze (all 0's - walls).
this.setBounds(0,0,aw+10,10+ah+yoff);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{Thread.sleep(500);} catch(Exception e) {} // Synch with system
this.addKeyListener(this);
g = getGraphics(); //g.setColor(Color.red);
setup();
}
public void paint(Graphics g) {} // override automatic repaint
public void setup()
{
g.setColor(Color.green);
g.fill3DRect(0,yoff,aw,ah,true); // fill raised rectangle
g.setColor(Color.black);
// showStatus("Generating maze...");
digout(mh-2,mw-2); // start digging!
// digout exit
M[mh-1][mw-2] = M[mh-2][mw-1] = 1;
drawblock(mh-2,mw-1);
solve(); // this is the function you will write for parts 1 and 2
play(); // for part 3
}
public static void main(String[] args)
{
int blocksize = bh, mheight = 41, mwidth = 41; // need to be odd
if (args.length==3)
{
mheight=Integer.parseInt(args[0]);
mwidth=Integer.parseInt(args[1]);
blocksize=Integer.parseInt(args[2]);
}
mazedfs W = new mazedfs(blocksize,mheight,mwidth);
}
public void drawblock(int y, int x)
{
g.setColor(Color.black);
g.fillRect(x*bw,yoff+(y*bh),bw,bh);
g.setColor(Color.yellow);
// following line displays value of M[y][x] in the graphical maze:
if (showvalue)
g.drawString(""+M[y][x],(x*bw)+(bw/2-4),yoff+(y*bh)+(bh/2+6));
}
void drawdot(int y, int x)
{
g.setColor(Color.red);
g.fillOval(x*bw,yoff+(y*bh),bw,bh);
try{Thread.sleep(dtime);} catch(Exception e) {}
}
/////////////////////////////////////////////////////////////////////
/* function to generate random maze */
public void digout(int y, int x)
{
M[y][x] = 1; // digout maze at coordinate y,x
drawblock(y,x); // change graphical display to reflect space dug out
int dir = (int)(Math.random()*4);
for (int i=0;i<4;i++){
int [] DX = {0,0,2,-2};
int [] DY = {-2,2,0,0};
int newx = x + DX[dir];
int newy = y + DY[dir];
if(newx>=0 && newx<mw && newy>=0 && newy<mh && M[newy][newx]==0)
{
M[y+DY[dir]/2][x+DX[dir]/2] = 1;
drawblock(y+DY[dir]/2,x+DX[dir]/2);
digout(newy,newx);
}
dir = (dir + 1)%4;}
} // digout
/* Write a routine to solve the maze.
Start at coordinates x=1, y=1, and stop at coordinates
x=mw-1, y=mh-2. This coordinate was especially dug out
after the program called your digout function (in the "actionPerformed"
method).
*/
public void solve()
{
int x=1, y=1;
Stack yourstack = null;
drawdot(y,x);
while(y!=mh-2 || x!=mw-2 && M[y][x]!=0){
int min = 0x7fffffff;
int DX = 0;
int DY = 0;
if (y-1>0 && min>M[y-1][x] && M[y-1][x]!=0){
min = M[y-1][x];
DX = 0;
DY = -1;
}//ifNORTH
if (y+1>0 && min>M[y+1][x] && M[y+1][x]!=0){
min = M[y+1][x];
DY = 1;
DX = 0;
}//ifSOUTH
if (x-1>0 && min>M[y][x-1] && M[y][x-1]!=0){
min = M[y][x-1];
DX = -1;
DY = 0;
}//ifWEST
if (x+1>0 && min>M[y][x+1] && M[y][x+1]!=0){
min = M[y][x+1];
DX = 1;
DY = 0;
}//ifEAST
M[y][x]++;
drawblock(y,x);
x = x+DX;
y = y+DY;
drawdot(y,x);
yourstack = new Stack(y,x,yourstack); // creates new stack for each coordinate travelled
}//while
while(yourstack != null){
yourstack = yourstack.tail;
drawdot(yourstack.y,yourstack.x); // this will traceback every box ive been through
}//while
} // solve
class Stack{
int x;
int y;
Stack tail;
public Stack(int a, int b, Stack t){
y = a;
x=b;
tail=t;
}
}//stackclass
///////////////////////////////////////////////////////////////
/// For part three (save a copy of part 2 version first!), you
// need to implement the KeyListener interface.
public void play() // for part 3
{
// code to setup game
}
// for part 3 you may also define some other instance vars outside of
// the play function.
// for KeyListener interface
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) // change this one
{
int key = e.getKeyCode(); // code for key pressed
System.out.println("YOU JUST PRESSED KEY "+key);
}
} // mazedfs
////////////
// define additional classes (stack) you may need here.
when you trace your path back you currently just go back to your stack - but thats not the shortest path...
...whenever you can go back check the values of M around you:
byte valueOfFieldNorthOfXY = M[x][y-1]; //x/y is your current position
byte valueOfFieldWesthOfXY = M[x-1][y];
byte ...;
byte ...; //and so on...
while the first while-loop in your solve-methode simplay solves the maze by flooding it the second while-method is for going back...
and when i say flooding i mean: each time a field has been passed by the 'walker' the value of M[x][y] has been increased by 1 (when the 'walker' has walked 3x over field 5/6 then the value from M[5][6] = 3)
so when you go back from the end (#40/50) to the start (#1/1), you do this algorith:
1) i stand on x/y
2) i check the values north/east/south/west of me
2a) if i come from north, then i ignore the north field
2 ) ... and so on...
2d) if i come from west , then i ignore the west field
3) i pick that direction, where the value is the least
4) put the current field int your packPathStack and walk to
the 'best' direction
5) repeat (go back to Nr.1) until you are #1/1
example
? 4 ? //i'm standing at X (x/y)
2 x f //? are values from walls or not yet considerd
? ? ? //f is where i come from
--> i pick direction WEST(2) because thats less than NORTH(4)
implement this algorithm and you a NEW stack i call it yourPathBackStack
Stack yourPathBackStack = new Stack();
while(x != 1 && y != 1 ){ //x/y = 1/1 = start - do it until you are there (Nr. 5)
// 1) i stand on x/y
int x = yourPathBackStack.x;
int y = yourPathBackStack.y;
// 2) i check the values north/east/south/west of me
byte valueOfFieldNorthOfXY = ... ; //as seen above
// 2a) if i come from north, then i ignore the north field
if (yourstack.tail.x == x && yourstack.tail.y == y-1){
//check - i DO come from north
//make then valueOfFieldNorthOfXY very high
valueOfFieldNorthOfXY = 100; //it's the same as ignoring
}
// 2 ) ... and so on...
// 2d) if i come from west , then i ignore the west field
if (yourstack.tail.x == x-1 && ...// as seen above
// 3) i pick that direction, where the value is the least
int direction = NORTH; //lets simply start with north;
byte maxValue = 100;
if ( valueOfFieldNorthOfXY < maxValue ){ //First north
maxValue = valueOfFieldNorthOfXY;
direction = NORTH;
}
if ( valueOfFieldWestOfXY < maxValue ){ //Then east
maxValue = valueOfFieldWestOfXY ;
direction = WEST;
}
//then the also other directions
if ( value ... //as seen above
// 4) put the current field int your yourPathBackStack and walk to
// the 'best' direction
int newx = x;
int newy = y;
if (direction == NORTH){ //direction has been caclulated above
newy = newy - 1;
}
if (direc ... //with all other direction)
yourPathBackStack = new Stack(newx, newy, yourPathBackStack );
drawdot(yourPathBackStack.y,yourPathBackStack.x);
}

Draw series of concentric circles with random settings

I'm really stuck on how to go about programming this. Need to draw a series of 8 concentric circles using Java drawArc method with following conditions
using import java.util.Random library
Provide for starting the drawings at random location (i.e., the x-y
cooridinate must be calculated randomly).
Provide a random color for each circle
Provide a random diameter for each circle
My current code is able to get random random color for each circle but not clear how to meet other random conditions
// Exercise 12.6 Solution: CirclesJPanel.java
// This program draws concentric circles
import java.awt.Graphics;
import javax.swing.JPanel;
public class ConcentricCircles extends JPanel
{
// draw eight Circles separated by 10 pixels
public void paintComponent( Graphics g )
{
Random random = new Random();
super.paintComponent( g );
// create 8 concentric circles
for ( int topLeft = 0; topLeft < 80; topLeft += 10 )
{
int radius = 160 - ( topLeft * 2 );
int r = random.nextInt(255);
int gr = random.nextInt(255);
int b = random.nextInt(255);
Color c = new Color(r,gr,b);
g.setColor(c);
g.drawArc( topLeft + 10, topLeft + 25, radius, radius, 0, 360 );
} // end for
}
}
// This program draws concentric circles
import javax.swing.JFrame;
public class ConcentricCirclesTest extends JFrame {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame=new JFrame("Concentric Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ConcentricCircles cCirclesJPanel = new ConcentricCircles();
frame.add(cCirclesJPanel);
frame.setSize(200,250);
frame.setVisible(true);
}//end main
}
Several points are key to such an exercise:
Start with constants for the number of circles and step size; the random number generator in particular only needs to be created once.
private static final int N = 8;
private static final int S = 32;
private static Random random = new Random();
Choose a random point whose coordinates fall within the drawing area.
// a random point inset by S
int x = random.nextInt(getWidth() - S * 2) + S;
int y = random.nextInt(getHeight() - S * 2) + S;
For each circle, find the diameter as a function of S, adding a random fraction of a step, and render the arc at the chosen point offset by the radius.
for (int i = 0; i < N; i++) {
g2d.setColor(…);
int d = (i + 1) * S + random.nextInt(S / 2);
int r = d / 2;
g2d.drawArc(x - r, y - r, d, d, 0, 360);
}
Resize the enclosing frame, which forces a repaint(), to see the effect.
As random colors are not always appealing, consider Collections.shuffle() on a List<Color>.
private final List<Color> clut = new ArrayList<Color>();
…
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor((float) i / N, 1, 1));
}
…
Collections.shuffle(clut);
…
g2d.setColor(clut.get(i));
Override getPreferredSize() to establsh the drawing panel's size.
private static final int W = S * 12;
private static final int H = W;
…
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
See also Initial Threads.

Categories