Drawing Geometric Primitives
The Java 2D API provides several classes that define common geometric objects such as points, lines, curves, and rectangles. These geometry classes are part of the java.awt.geom package.
The PathIterator interface defines methods for retrieving elements from a path.
The Shape interface provides a set of methods for describing and inspecting geometric path objects. This interface is implemented by the GeneralPath class and other geometry classes.
All examples represented in this section create geometries by using java.awt.geom package and then render them by using the Graphics2D class. To begin you obtain a Graphics2D object, for example by casting the Graphics parameter of the paint() method.
Point
The Point class creates a point representing a location in (x,y) coordinate space. The subclasses Point2D.Float and Point2D.Double provide correspondingly float and double precision for storing the coordinates of the point.
To create a point with the coordinates 0,0 you use the default constructor, Point2D.Double() .
You can use the setLocation method to set the position of the point as follows:
- setLocation(double x, double y) – To set the location of the point- defining coordinates as double values.
- setLocation(Point2D p) – To set the location of the point using the coordinates of another point.
Also, the Point2D class has methods to calculate the distance between the current point and a point with given coordinates, or the distance between two points.
The Line2D class represents a line segment in (x, y) coordinate space. The Line2D. Float and Line2D.Double subclasses specify lines in float and double precision. For example:
This class includes several setLine() methods to define the endpoints of the line.
Alternatively, the endpoints of the line could be specified by using the constructor for the Line2D.Float class as follows:
- Line2D.Float(float X1, float Y1, float X2, float Y2)
- Line2D.Float(Point2D p1, Point2D p2)
Use the Stroke object in the Graphics2D class to define the stroke for the line path.
Curves
The java.awt.geom package enables you to create a quadratic or cubic curve segment.
Quadratic Curve Segment
The QuadCurve2D class implements the Shape interface. This class represents a quadratic parametric curve segment in (x, y) coordinate space. The QuadCurve2D.Float and QuadCurve2D.Double subclasses specify a quadratic curve in float and double precision.
Several setCurve methods are used to specify two endpoints and a control point of the curve, whose coordinates can be defined directly, by the coordinates of other points and by using a given array.
A very useful method, setCurve(QuadCurve2D) , sets the quadratic curve with the same endpoints and the control point as a supplied curve. For example:
Cubic Curve Segment
The CubicCurve2D class also implements the Shape interface. This class represents a cubic parametric curve segment in (x, y) coordinate space. CubicCurve2D.Float and CubicCurve2D.Double subclasses specify a cubic curve in float and double precision.
The CubicCurve2D class has similar methods for setting the curve as the QuadraticCurve2D class, except with a second control point. For example:
Rectangle
Classes that specify primitives represented in the following example extend the RectangularShape class, which implements the Shape interface and adds a few methods of its own.
These methods enables you to get information about a shape’s location and size, to examine the center point of a rectangle, and to set the bounds of the shape.
The Rectangle2D class represents a rectangle defined by a location (x, y) and dimension (w x h). The Rectangle2D.Float and Rectangle2D.Double subclasses specify a rectangle in float and double precision. For example:
The RoundRectangle2D class represents a rectangle with rounded corners defined by a location (x, y), a dimension (w x h), and the width and height of the corner arc. The RoundRectangle2D.Float and RoundRectangle2D.Double subclasses specify a round rectangle in float and double precision.
The rounded rectangle is specified with following parameters:
- Location
- Width
- Height
- Width of the corner arc
- Height of the corner arc
To set the location, size, and arcs of a RoundRectangle2D object, use the method setRoundRect(double a, double y, double w, double h, double arcWidth, double arcHeight) . For example:
Ellipse
The Ellipse2D class represents an ellipse defined by a bounding rectangle. The Ellipse2D.Float and Ellipse2D.Double subclasses specify an ellipse in float and double precision.
Ellipse is fully defined by a location, a width and a height. For example:
To draw a piece of an ellipse, you use the Arc2D class. This class represents an arc defined by a bounding rectangle, a start angle, an angular extent, and a closure type. The Arc2D.Float and Arc2D.Double subclasses specify an arc in float and double precision.
The Arc2D class defines the following three types of arcs, represented by corresponding constants in this class: OPEN, PIE and CHORD.
Several methods set the size and parameters of the arc:
- Directly, by coordinates
- By supplied Point2D and Dimension2D
- By copying an existing Arc2D
Also, you can use the setArcByCenter method to specify an arc from a center point, given by its coordinates and a radius.
Графика в Java. Graphics
Графику в Java обслуживают классы Graphics и Graphics2D.
Работа с графикой осуществляется в графическом контексте элементов, унаследованных от класса Component. Понимать это можно так: на элементах управления, например, JFrame, JPanel, JButton и других, есть возможность рисовать. Такие элементы обладают графическим контекстом, в этом контескте мы и рисуем. Всё, что нарисуем в контексте будет показано на элементе. Классы Graphics и Graphics2D нужны для работы с графическим контекстом. Мы должны получить экземпляр такого класса и, используя его методы, рисовать. Получить экземпляр контекста можно в методе paint:
этот метод наследуется из класса Component. Аргумент Graphics g создаётся системой, а мы берём его в готовом виде и используем для рисования. При создании элемента метод paint будет вызван автоматически.
Начнём изучать работу с графикой в Java с класса Graphics.
Graphics
Рассмотрим простой пример использования методов класса Graphics в Java:
Получаем: 
Ниже разбираются все методы, использованные в примере.
Как начертить прямую линию?
Метод drawLine класса Graphics начертит прямую линию:
здесь 20, 30 — это координаты x, y начала линии,
360, 30 — координаты конца линии.
Как задать цвет?
Метод setColor класса Graphics сделает текущим новый цвет:
Аргументы конструктора new Color(0, 0, 255) — это красный, зелёный и синий цвета соответственно (rgb).
Как задать rgb цвета? В примере задан чисто синий цвет, т.к. значения других составляющих равны нулю. Вот чисто красный цвет:
А это чисто зеленый цвет:
Значения составляющих цвета изменяются от 0 до 255.
Светло-синий цвет, который мы использовали для заливки прямоугольника:
Как задать цвет фона?
Задать цвет фона можно методом setBackground:
Как нарисовать прямоугольник?
Методом drawRect класса Graphics:
20, 40 — это координаты верхнего левого угла прямоугольника;
340 — длина;
20 — высота прямоугольника.
Как залить прямоугольник цветом?
Методом fillRect класса Graphics:
Как нарисовать прямоугольник с закругленными углами?
Методом drawRoundRect класса Graphics.
Сопряжение, т.е. закругление на углах, делается с помощью частей овала.
первые 4 аргумента как у обычного прямоугольника. Пятый аргумент — 20 — это ширина прямоугольника, в который вписана часть овала сопряжения. Шестой аргумент — 15 — это высота прямоугольника, в который вписана часть овала сопряжения.
Как нарисовать овал?
Методом drawOval класса Graphics:
Аргументы определяют прямоугольник, в который вписан овал.
Как нарисовать окружность?
Методом drawOval класса Graphics:
Аргументы определяют прямоугольник, в который вписана окружность. Здесь рисуем овал, но длина и высота описанного прямоугольника равны, что и даёт окружность.
Как нарисовать дугу?
Методом drawArc класса Graphics:
первые 4 аргумента как у обычного прямоугольника. Пятый аргумент — 0 — это угол, от которого отсчитывается угол самой дуги. 180 — это угол дуги. Углы отсчитывают от горизонтальной оси: по часовой стрелке отрицательное направление, протв — положительное. В примере 180 градусов (величина дуги) отсчитываем от горизонтальной линии.
Как нарисовать многоугольник?
Методом drawPolygon класса Graphics:
Здесь создаём объект класса Polygon. arrayX — это х-координаты вершин многоугольника, arrayY — это y-координаты вершин многоугольника, 8 — число вершин многоугольника.
Как создать объект точки?
Для этого используем класс Point:
аргументы — это x, y координаты.
Как определить, что точка принадлежит многоугольнику?
Используем метод класса Polygon contains для определения лежит ли точка в многоугольнике.
Как вывести строку?
Методом drawString класса Graphics:
строка «Yes» будет выведена от точки с координатами 50, 190.
Как задать шрифт?
Для этого используем класс Font:
где «Tahoma» — название шрифта,
Font.BOLD|Font.ITALIC — жирный шрифт с наклоном,
40 — высота шрифта.
После задания шрифта мы делаем его текущим и выводим строку этим шрифтом:
Как задать цвет текста?
Чтоб задать цвет текста создадим и установим в графический контекст новый цвет:
Здесь мы создали чисто синий цвет. А теперь выводим строку синим цветом:
Как начертить график?
Как график функции начертить? Сначала начертим координатные оси:
А теперь построить график функции можно просто. Для этого используем метод drawPolyline класса Graphics:
График строим по точкам, xArray – это x-координаты точек, yArray – y-координаты точек графика, nPoint — это число точек.
Наш график являет собой кривую намагничивания. Но почему график такой угловатый (см. картинку выше)? Если взять больше точек, то график будет более плавным.
Нарисуйте линию на Java

Класс Java.awt.Graphics в Java формирует основу для многих таких функций рисования и графики. Это непонятный класс, поскольку фактическое действие рисования зависит от системы и устройства. В этом уроке мы нарисуем линию на Java.
Мы запустим программу, импортировав необходимые пакеты. Мы импортируем пакеты java.applet.Applet , java.awt и java.awt.event из библиотеки.
Метод drawLine() класса Graphics используется для рисования линии заданного цвета между двумя точками.

В приведенном выше примере мы создали две строки, а также отобразили текст. Сначала мы объявили класс DrawLine , который расширяет класс Applet (родительский класс). Внутри класса мы объявили основной метод. Здесь оператор Frame drawLineApplet = new Frame() создает окно апплета для вывода.
Функция drawLineApplet.setSize() используется для установки размера окна апплета, а функция drawLineApplet.setVisible(true) используется для отображения рамки на экране. Мы используем команду system.exit(0) для выхода из фрейма апплета.
Метод paint здесь используется для установки цвета, шрифта и координат линии, которую нужно нарисовать. Шрифт меняем с помощью функции setFont() . Функция drawString() здесь отображает некоторый текст во фрейме вывода. Мы меняем цвет первой линии с помощью setColor() , а затем координаты x и y линии в функции drawLine() . Точно так же мы указываем координаты и цвет для второй строки.
How to draw lines in Java
I’m wondering if there’s a funciton in Java that can draw a line from the coordinates (x1, x2) to (y1, y2)?
What I want is to do something like this:
And I want to be able to do it at any time in the code, making several lines appear at once.
I have tried to do this:
But this gives me no control of when the function is used and I can’t figure out how to call it several times.
Hope you understand what I mean!
P.S. I want to create a coordinate system with many coordinates.
![]()
10 Answers 10
A very simple example of a swing component to draw lines. It keeps internally a list with the lines that have been added with the method addLine. Each time a new line is added, repaint is invoked to inform the graphical subsytem that a new paint is required.
The class also includes some example of usage.
Store the lines in some type of list. When it comes time to paint them, iterate the list and draw each one. Like this:
Screenshot

DrawLines
![]()
You need to create a class that extends Component. There you can override the paint method and put your painting code in:
Put this component into the GUI of your application. If you’re using Swing, you need to extend JComponent and override paintComponent, instead.
As Helios mentioned, the painting code actually tells the system how your component looks like. The system will ask for this information (call your painting code) when it thinks it needs to be (re)painted, for example, if a window is moved in front of your component.
In your class you should have:
Then in code if there is needed you will change x1, y1, x2, y2 and call repaint(); .
I understand you are using Java AWT API for drawing. The paint method is invoked when the control needs repainting. And I’m pretty sure it provides in the Graphics argument what rectangle is the one who needs repainting (to avoid redrawing all).
So if you are presenting a fixed image you just draw whatever you need in that method.
If you are animating I assume you can invalidate some region and the paint method will be invoked automagically. So you can modify state, call invalidate, and it will be called again.
To give you some idea:
You can use the getGraphics method of the component on which you would like to draw. This in turn should allow you to draw lines and make other things which are available through the Graphics class
I built a whole class of methods to draw points, lines, rectangles, circles, etc. I designed it to treat the window as a piece of graph paper where the origin doesn’t have to be at the top left and the y values increase as you go up. Here’s how I draw lines:
In the example above, (x0, y0) represents the origin in screen coordinates and scale is a scaling factor. The input parameters are to be supplied as graph coordinates, not screen coordinates. There is no repaint() being called. You can save that til you’ve drawn all the lines you need.
It occurs to me that someone might not want to think in terms of graph paper:
Notice the use of Graphics2D . This allows us to draw a Line2D object using doubles instead of ints. Besides other shapes, my class has support for 3D perspective drawing and several convenience methods (like drawing a circle centered at a certain point given a radius.) If anyone is interested, I would be happy to share more of this class.