Drawing Lines in Java

Introduction

A line connects two points in space. In Java, a line can be thought of as a graphics primitive that will connect two coordinates on your screen. A line can be drawn by using two objects. You can either use the Graphics object or the Graphics2D object. The methods for both the objects are given below:

Using a Graphics Object

//x1, x2, y1, and y2 are all coordinates
Syntax: object.drawLine (int x1, int y1, int x2, it y2)

Example in Java

import java.awt.*;
import javax.swing.*;
public class New extends JFrame {
public New() {
//Defining the length and breadth of the frame
setSize(1080. 960)
setVisible(true);
setDefaultCloseOperation( EXIT_ON_CLOSE);
}
public void lineDrawing (Graphics g) {
g.drawLine (0, 480, 960, 480);
}
public static void main (String args []) {
New n = new New ();
}
}

 

Using a Graphics2D Object

Syntax: object.draw(line);

Example in Java

import java.awt.Graphics ;
import java.awt.Graphics2D ;
import java.awt.geom.Line2D ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
public class LineDemo extends JFrame
{
public Demo()
{
JPanel panel = new JPanel();
getContentPane().add(panel);
//Setting size of panel
setSize(550, 300);
}
public void paint ( Graphics gp )
{
super.paint ( gp );
Graphics2D graphics = (Graphics2D) gp;
//Creating a new line by specifying the x and y coordinates of the two points that the line will //connect
Line2D line = new Line2D.Float ( 0, 480, 960, 480 );
graphics.draw( Line );
}
public static void main ( String args [] )
{
//Creating an object of the main class
LineDemo demo = new LineDemo ();
demo.setVisible ( true );
}
}

 

OUTPUT

The output will be a line that traverses the points (0, 480) and (960, 480). Both the snippets of code will produce the same line but by using different object types in the process.

You can add other features to the line such as thickness, colour, and style (dotted, dashed) using other methods and CSS.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.