I am writing a program that accepts coordinates from the user and drawing some shapes on the screen with stars(*)
e.g Rectangle i.e rectangle=100,150,50,50 as x,y,width,height. how can I do i开发者_高级运维t??
I think that this tutorial is very useful for you: http://download.oracle.com/javase/tutorial/2d/geometry/primitives.html
What 'drawing with stars' is? If this is text mode with monospaced font, you'll need to print it in horizontal lines of stars, calculating right lengths. For rectangles this is easy, for triangles, a bit less easy, pentagon is just a combination of a rectangle and some triangles. See Bresenham algorithm for inspiration.
Also note that text mode resolution is quite poor; standard terminal window in only 80 chars wide, and you can hardly have it far wider than say 200-300 chars, so correct rounding is important.
If it's only rectangles, then putting the following in your paint method should work...
int xIncrement = (int)g.getFont().getStringBounds("*", null).getWidth();
int yIncrement = (int)g.getFont().getStringBounds("*", null).getHeight();
for(int i = y; i < y + height; i += xIncrement)
for(int j = x; j < x + width; j += yIncrement)
g.drawString("*", j, i);
For triangles and other shapes it's a bit tougher, but you can figures out the gradients of the lines separating the points, and therefore get the initial x for each line.
Generally, try to avoid 'star drawing'...
Unless you are referring to GUI, the Y coordinate can be the amount of lines you have to 'skip' and the x coordinate resemble the amount of spaces you have enter in the line.
So basically, x = 2 and y = 3 means that you will have to go down 3 lines and move 2 spaces to the right.
Below is from javadoc
x - the new x coordinate for the top-left corner of this Rectangle y - the new y coordinate for the top-left corner of this Rectangle
精彩评论