How to Draw a Line in Java With Line2D

How to Draw a Line in Java With Line2D thumbnail
Line2D is a data type in Java used to draw lines.

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."

Related Searches:

References

  • Photo Credit Ablestock.com/AbleStock.com/Getty Images

Comments

You May Also Like

  • How to Draw a House

    Drawing a house involves laying out the basic construction, using simple shapes like squares and triangles to indicate the frame, door, windows,...

  • How to Draw Shapes in Java Applet

    Java applets are programs written in the object-oriented programming language Java. Applets tend to perform one basic task, and do so in...

  • Paint Method in a Java Applet

    Every Java Applet contains a "paint" method. The applet class will automatically handle the drawing of all user interface elements to the...

Related Ads

Featured