Drawing in a window in Java

Lesson 4 of 8 · Java – graphical applications

A panel for drawing

Swing components in Java do not have to be shown in a single color. We can draw on them, both simple geometric shapes (points, lines, a circle, an ellipse, a rectangle) and complex geometric figures (polylines, complex open and closed curves). In other words, a drawing can be made on any kind of component (JPanel, JButton, etc.). To turn a single-colored component, e.g. a panel, into a component with a drawing, that component (the panel in this example) must belong to a class that inherits JComponent or one of the classes that already inherit JComponent, e.g. the class JPanel. This class must also override the inherited method paint (it is in the JComponent class).

This method is called automatically when the graphics are drawn for the first time, or when the size of the window changes, and it can also be called from code:

repaint();

The paint method gets as a parameter an object of the class Graphics, which contains the methods needed for drawing. Calling the right method draws a certain shape. For example, to draw an ellipse inscribed in a rectangle of width 400 and height 300, which is 200 away from the origin along the X axis and 100 along the Y axis, the code of the paint method would be:

@overriding
public void paint(Graphics g) {
    g.drawOval(200, 100, 400, 300);
}

Here g is the drawing tool, i.e. the object that contains the drawing methods. This paint method overrides a method of one of the inherited classes, in this case the class JComponent. The class JPanel inherits JComponent, and this overridden paint method must be in a class that inherits the JPanel class:

public class Crtez extends JPanel {
    @overriding
    public void paint(Graphics g) {
        // Some code
    }
}

Video lessons

Drawing in a window – Graphics

EXAMPLE: Geometric shapes in Java

Task text

  • Draw a 400x400 square at a distance of 200 on the X axis and 200 on the Y axis.
  • Draw a diagonal of the square
  • Inscribe a circle in the square

Solution

The object on which the drawing is made belongs to the class Crtez (Drawing), which inherits the class JPanel. If we right-click inside the body of such an empty class and choose Insert Code -> Override Method from the context menu, we get the inherited classes and the methods in them that can be overridden:

 Drawing in a window. Overriding a method
Figure 1: Drawing in a window. Overriding a method

The drawing method paint is in the class JComponent, so select it and click the button Generate to insert it into the class:

Drawing in a window. Overriding a method – step 2
Figure 2: Drawing in a window. Overriding a method – step 2

After this, the following method is inserted:

public class Crtez extends JPanel {
    @Override
    public void paint(Graphics g) {
        super.paint(g);
    }
}
Figure 3: Drawing in a window. Overriding a method – paint

The code inserted inside it is: super.paint(g);

which calls the inherited paint method. This can be used to draw the background color of the inherited panel.

The drawing we want to get looks like the picture below:

Drawing in a window. Geometric shapes
Figure 4: Drawing in a window. Geometric shapes.

To draw this, the code in the paint method looks like this:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Crtez extends JPanel {
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(Color.blue); // sets the drawing color
        /*
* draws a 400x400 square at the coordinate (100,100)
*/
        g.drawRect(100, 100, 400, 400);

        g.drawLine(100, 500, 500, 100); // diagonal
        g.drawOval(100, 100, 400, 400);
    }
}
Figure 5: Drawing in a window. Geometric shapes – code.

First the drawing color is set to blue with the method setColor of the Graphics object received as the parameter of the method. Then a square is drawn with the method drawRect (draws a rectangle), which needs 4 parameters. The first two are the X and Y coordinates of the top left corner of the rectangle relative to the top left corner of the panel, where the origin is, while the third and fourth parameters are the width and height of the rectangle. Since the rectangle has equal width and height, it is actually a square.

The method drawLine draws a line between the points (100,500) and (500,100).

The method drawOval draws an ellipse (a circle) inscribed in a rectangle (a square) whose parameters are identical to the parameters of the drawRect method.

These shapes can be drawn in another way: a geometric shape is created as an object of a certain API class that implements the interface Shape. Then the method draw is called and the created shape is passed to it for drawing. This method does not exist in the class Graphics, but in the inherited class Graphics2D from the package java.awt.

The Graphics2D class in Java

The classes used to make various drawing objects, which implement the interface Shape, are in the package java.awt.geom. We use the classes Ellipse2D, Line2D and Rectangle2D to implement the objects circle, diagonal and square. Inside the class these objects are first declared as attributes of the class Crtez1, while the objects are created in the constructor:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;

public class Crtez1 extends JPanel {
    /*
* Deklaracija atributa
*/
    Ellipse2D krug;
    Rectangle2D kvadrat;
    Line2D dijagonala;

    public Crtez1() {
        // creates the circle
        krug = new Ellipse2D.Double(100, 100, 400, 400);
        // creates the diagonal
        dijagonala = new Line2D.Double(100, 500, 500, 100);
        // creates the square
        kvadrat = new Rectangle2D.Double(100, 100, 400, 400);
    }
}
Figure 7: Drawing in a window. Graphics2D. Creating geometric shapes – code.

All three classes have the variants Double and Float, and in this case the Double variant is clearly used. All 4 parameters of the circle and the square are the same as for the methods drawOval and drawRect of the Graphics object in the first version of the task.

The paint method now looks like this:

@Override
public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2 = (Graphics2D)g; // casting
    g2.setColor(Color.BLUE); // sets the drawing color to blue

    g2.draw(krug); // draws the circle
    g2.draw(dijagonala); // draws the diagonal
    g2.draw(kvadrat); // draws the square
}
Figure 8: Drawing in a window. Geometric shapes – code. Drawing with the paint method

The objects g2 and g have different types, so a cast is needed. This class has the same graphics as the class Crtez. If we want, for example, to fill the circle with color, we would use the fill method instead of draw:

g2.fill(krug);

After starting, the application would look like this:

Crtanje u prozoru. Geometrijski oblici. Kompletna grafika
Figure 9: Drawing in a window. Geometric shapes. The complete graphics

The panel of the class Crtez or Crtez1 is connected with the main window in the main class:

import javax.swing.JFrame;

public class GraphicsCrtanje extends JFrame {
    public GraphicsCrtanje() {
    }

    public static void main(String[] args) {
        GraphicsCrtanje win = new GraphicsCrtanje();
        win.setSize(600, 600);
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Crtez1 crtez = new Crtez1();
        win.setContentPane(crtez);
        win.setVisible(true);
    }
}
Figure 10: Drawing in a window. Geometric shapes. The complete graphics – code

The main class (GraphicsCrtanje) inherits JFrame, which is why the object win, which is actually the main window of the application, is of the class GraphicsCrtanje.

Class Method Description
java.awt.Graphics drawRect(int x,int y, int w, int h) Draws a rectangle whose top left corner is at the coordinates (x,y), w – width h – height
java.awt.Graphics drawLine(int x1,int y1, int x2, int y2) Draws a line from the point (x1,y1) to the point (x2,y2)
java.awt.Graphics drawOval(int x,int y, int w, int h) Draws an ellipse; the top left corner of the rectangle drawn around the ellipse is at the coordinates (x,y), w – width h – height
java.awt.Graphics drawRoundRect(int x,int y, int w, int h,int arcW, int arcH) Draws a rectangle with rounded edges whose top left corner is at the coordinates (x,y), w – width h – height arcW – horizontal diameter of the arc at all 4 corners arcH – vertical diameter of the arc at all 4 corners
java.awt.Graphics drawArc(int x,int y, int w, int h, int pocU, int krajU) Draws an arc of an ellipse whose bounding rectangle has its top left corner at the coordinates (x,y), w – width h – height pocU – starting angle of the arc krajU – angular extent of the arc
java.awt.Graphics drawString(String str, int x,int y) Draws the String str with its baseline starting at the coordinates (x,y)
java.awt.Graphics2D draw(Shape shape) Draws the outline of the shape object (e.g. Rectangle2D, Ellipse2D, Line2D)
java.awt.Graphics2D fill(Shape shape) Fills the inside of the shape object with the current color
java.awt.Graphics fillRect(int x,int y, int w, int h) Fills a rectangle whose top left corner is at the coordinates (x,y), w – width h – height
java.awt.Graphics fillOval(int x,int y, int w, int h) Fills an ellipse; the top left corner of the rectangle drawn around the ellipse is at the coordinates (x,y), w – width h – height

Check your knowledge

Open the quiz

Quiz: Drawing in a window

1. In which method do we draw on a component?




2. What does g.drawRect(10, 20, 100, 50) do?




3. Where is the point (0, 0) on a component?




4. How do we ask for the component to be drawn again?