by Dinesh Thakur

Draw a straight line is one of the easiest things to do with Java2D. This is achieved through the Line2D class, whose constructor accepts four parameters, namely the coordinates of the start and end respectively.

In Line2D Java Example we are using package java.awt.geom.*. This class provides a line segment in (x, y) coordinate space. Following is at able that lists some of the Constructors and methods of Line2D class:


Constructors and Methods


Line2D.Double ()

Creates a Line2D from (0, 0) to (0, 0).

Line2D.Double (double X1, double Y1, double X2, double Y2)

Creates a Line2D from (X1, Y1) to (X2, Y2).

Line2D.Float ()

Creates a Line2D from (0, 0) to (0, 0).

Line2D.Float (float X1, float Y1, float X2, float Y2)

Creates a Line2D from (X1, Y1) to (X2, Y2).

intersects (double X, double Y, double W, double H)

Returns true if the rectangle described by (X, Y, Width, Height) intersects the Line.

intersectsLine (double X1, double Y1, double X2, double Y2)

Returns true if the line from (X1, Y1) to (X2, Y2) intersects the Line.

intersectsLine (Line2D L)

Returns true if the line L intersects the Line.

setLine (double X1, double Y1, double X2, double Y2)

Sets the ends of the line as (X1, Y1) and (X2, Y2).


import java.applet.Applet;

import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.image.*;
public class Draw2DLineExample extends Applet {
public static void main(String[] args) {
Frame Draw2DLine = new Frame("Draw Line2D Example");
Draw2DLine.setSize(350, 250);
Applet Draw2DLineExample = new Draw2DLineExample();
Draw2DLine.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
  public void paint(Graphics g) {
    g.setFont(new Font("Arial",Font.BOLD,14));
    g.drawString("Draw 2D Line Example", 50, 40);
    g.setFont(new Font("Arial",Font.BOLD,10));
    g.drawString("", 200, 205);
                Graphics2D G2D = (Graphics2D)g;
                G2D.setStroke(new BasicStroke(3.0f));
                Line2D L2D = new Line2D.Float(50.0f, 50.0f, 200.0f, 200.0f);

Line2D Java Example