Basic Drawing on Screen

  • We have seen a basic use of the MWT and widgets libraries. Before going further let’s see how to write directly on a display using both Displayable and GraphicsContext classes.

  • A Displayable represents what can be shown on a screen, a GraphicsContext provides access to a modifiable (readable and writable) pixel buffer to be associated with an Image or a Displayable.

  • It is then possible to have access to a drawable interface that represents a pixelated version of the Display.

    public static void main(String[] args){
       Displayable myDisplayable = new Displayable() {
          protected void render(GraphicsContext g) {
             // Draws a yellow line.
             Painter.drawLine(g, 0, 0, 100, 50);
          public boolean handleEvent(int event) {
             return false;
  • This draws a line from the coordinates of the display (0,0) to (100,50).


Drawing Basic Shapes

  • The Painter class contains several primitives to draw geometric objects.

  • The code below draws each component with the selected color (yellow, purple, green).

  • The drawLine() method uses the starting and finishing point with x and y coordinates.

  • Fill rectangle and ellipse methods use x and y coordinates and also width and height.

  • Draw circle uses x and y and a diameter.

    Painter.drawLine(g, 0, 0, 100, 50);
    Painter.fillRectangle(g, 10, 20, 100, 20);
    Painter.fillEllipse(g, 120, 50, 20, 100);
    Painter.drawCircle(g, 50, 50, 100);

Drawing Images

  • The Painter class contains several primitives to draw images.

    Image image = Image.getImage("/images/microej_logo.png");
    // Draws the image at x,y coordinates (150, 50).
    Painter.drawImage(g, image, 150, 50);

Drawing Thick Shapes

  • The ShapePainter class offers a set of primitives to render thick shapes with or without anti-aliasing.

  • The code below shows how to draw a thick faded line.

    // Draws a thick yellow line.
    ShapePainter.drawThickFadedLine(g, 20, 20, 100, 80, 10, 6, Cap.ROUNDED, Cap.PERPENDICULAR);
    // Draws a thick green circle.
    ShapePainter.drawThickFadedCircle(g, 130, 20, 100, 20, 2);

Next step: Animation