How to Draw a Line in Java With Line2D
Java 2D is an application programming interface in the Java programming language used to process relevant programming classes, such as for shapes, and to test, draw or print them. This ability lies within the Graphics2D class. You can customize the length and orientation of a line in Line2D by inputting the start and stop coordinate points. For the data type Line2D(x1, y1, x2, y2), the first set of two numbers defines the beginning coordinate and the second set defines the end coordinate.
Instructions
-
-
1
Import the Graphics, Graphics2D and Line2D packages, typing in the calls before the rest of your code, using the "import" keyword. Your code should look like this:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
-
2
Override the "paint" method to instruct the compiler to draw a line when called. The completed method should appear something like this:
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g1;
Line2D line = new Line2D.Double(50, 50, 100, 100)
g2.draw(line);
}
You can vary the size of the line by changing the numbers within the parentheses.
-
-
3
Implement the method into your larger program. The line needs a frame which can be constructed by extending the JFrame class to your own class by use of the keyword "extends."
-
1
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images