How to Draw a Diamond in Java
Although Java does not include any default methods for drawing a diamond, it is relatively easy to create one yourself. This method will take a x coordinate and a y coordinate that mark the upper-left corner of the rectangle that encompasses your diamond. For example, if the y coordinate of the highest point on the diamond is 50 and the x coordinate of the leftmost point on the diamond is 25, the bounding coordinates will be 25 and 50. The method will also take a value for the height of the diamond and a value for the width of the diamond.
Instructions
-
Create a JFrame to Draw On
-
1
Start a new project in the Integrated Development Environment, or IDE, that you are most experienced with.
-
2
Create a new class called "DrawingComponent" in your project. Type "extends Component" immediately after "DrawingComponent" but before the opening bracket at the end of the class declaration.
-
-
3
Type the following code above the DrawingComponent class's declaration to import the required files into the class:
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath; -
4
Add a new paint method to override the component's default paint method. Insert the following code between the opening and closing brackets of the DrawingComponent class:
public void paint(Graphics g) {}
-
5
Create a new JFrame in your project's main method and add your custom drawing component to it with this code:
javax.swing.JFrame frame = new javax.swing.JFrame();
int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawingComponent());
Draw a Diamond
-
6
Create a new method in the DrawingComponent class by adding this code between the class's opening and closing brackets, but outside of the other methods in the class:
GeneralPath createDiamond(int x, int y, int width, int height){}
-
7
Enter the following code inside the createDiamond method to define a new GeneralPath with four lines:
GeneralPath diamond = new GeneralPath(GeneralPath.WIND_EVEN_ODD,4); -
8
Calculate the four points of the diamond given the values passed into the method. Each time you calculate a point, guide the path through that point. Use the following code to accomplish this:
x+=width/2;
diamond.moveTo(x, y);
x+=width/2;
y+=height/2;
diamond.lineTo(x,y);
x-=width/2;
y+=height/2;
diamond.lineTo(x,y);
x-=width/2;
y-=height/2;
diamond.lineTo(x,y); -
9
Close the GeneralPath object to turn it into a completed diamond and then return it with this code:
diamond.closePath();
return diamond; -
10
Call the createDiamond method inside of the paint method and pass the result to an instance of Graphics2D to draw the diamond with the following code:
Graphics2D g2d = (Graphics2D) g;
g2d.draw(createDiamond(100,100,50,100));
-
1