Draw a draggable triangle in Java

This example shows how to draw a triangle on a JFrame and make it draggable so it can be moved around by using the mouse. The example contains two classes, one which is the main frame (the JFrame) and one that extends JPanel that does the actual painting and that implements the necessary interfaces needed to make the triangle draggable.

Continue reading

Drawing a Rectangle using Java 2D Graphics API

This Java source code example shows how to draw a rectangle using the Java 2D Graphics API.
The rectangle is drawn on a JFrame but could be drawn on other AWT or Swing components as well.
All the painting work takes place in a method called paint(Graphics g). The paint method is called automatically when the JFrame is displayed so there is no need for an explicit call to the method.

Continue reading

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.

Continue reading

Drawing a String using Java 2D Graphics API

This example shows how to draw a String on a JFrame using the Java 2D Graphics API.
We cast the graphics object that is sent to the paint method as an argument to an Graphics 2D object, and then call the drawString() method on it.
The first parameter is the string to be drawn, the second is the X coordinate, and the third parameter is the Y coordinate.
Both coordinates has the top left corner as origin, so according to the code below the line will be drawn 100 pixels down and 20 pixels in from the left margin.

Continue reading