Drawing a Line using Java 2D Graphics API



This Java source code example shows how to draw a line using the Java 2D Graphics API.
In this example we draw on a JFrame, but it could easily be any other AWT or Swing component, like an Applet or JPanel.
First we need to cast the graphics object to a Graphics2D object. Then we create an instance of the Line2D class which takes four parameters.
The first and second parameters represents the starting point (X, Y) of the line to be drawn. The origin is the top left corner (= coordinates 0, 0),
so this means that our line should start to be drawn 100 pixels from the left side and 100 pixels down from the top.
The third and fourth parameters represents the ending point of the line, to the line ends at 250 pixels from the left side and 260 pixels from the top of the frame window.
Finally the draw() method of the Graphics2D object is called with the Line2D instance as argument.

This is what it looks like after drawing the line using the Java 2D API:

Drawing a line with the Java 2D Graphics API

This is the code of the entire JFrame class which is possible to execute by itself.







Search for more Java info on this site here:
Custom Search


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">