Java Drawing Arrays Graphics


Java Drawing Arrays Graphics

Summary: By the end of this tutorial "Java Drawing Arrays Graphics", you will be comfortable in drawing arrays with graphics.

Apart other graphics, Java also supports drawing characters from character and byte arrays. Java comes with an option of drawing complete array or part of the array.

Supporting methods from java.awt.Graphics class

1. void drawChars(char charArray[], int offset, int numOfChars, int x, int y): Draws characters specified by numOfChars from character array charArray beginning from offset. These characters are drawn at x and y coordinates in the frame.

2. void drawBytes(byte byteArray[], int offset, int numOfBytes, int x, int y): Draws characters specified by numOfBytes from byte array byteArray beginning from offset. These bytes are drawn at x and y coordinates in the frame.

As can be seen, the methods are drawChars() and drawBytes() that take a char array and byte array as the first parameter. Offset indicates the distance from the starting position from where characters in the array are to be drawn; 0 indicates the starting position. numOfChars indicates the number of characters to be drawn and x and y are the positions in the frame where the characters are to be drawn.

The following program uses the above methods.

import java.awt.*;
public class ArraysDrawing extends Frame
{
  public ArraysDrawing()
  {
    setTitle("Full or Part Array");
    setSize(325, 300);
    setVisible(true);
  }
  public void paint(Graphics g)
  {
    g.setFont(new Font("Serif", Font.PLAIN, 15));
    char letters[] = { 'U', 'n', 'i', 't', 'y', 'I', 'n', 'D', 'i', 'v', 'e', 'r', 's', 'i', 't', 'y' };
    g.drawChars(letters, 0, letters.length, 50, 70);  // to print all             
    g.drawChars(letters, 6, 7, 50, 90);            // to print a few
               
    byte alphabets[] = { 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107 };
    g.drawBytes(alphabets, 0, alphabets.length, 50, 130);  
    g.drawBytes(alphabets, 4, 5, 50, 150);             
  }
  public static void main(String args[])
  {
    new ArraysDrawing();
 }
}

Java Drawing Arrays Graphics
Output screen of ArraysDrawing.java of Java Drawing Arrays Graphics

char letters[] = { 'U', 'n', 'i', 't', 'y', 'I', 'n', 'D', 'i', 'v', 'e', 'r', 's', 'i', 't', 'y' };
g.drawChars(letters, 0, letters.length, 50, 70);
g.drawChars(letters, 6, 7, 50, 90);

letters is the character array. First drawChars() method prints complete array. The second drawChars() method prints 7 characters starting from 6th. Remember index numbering starts from 0 in arrays. 50 and 90 are the x and y coordinates where the letters are to be drawn. Similarly with byte array also.

The frame you get do not close when clicked over the close icon on the title bar of the frame. It requires extra code.

Leave a Comment

Your email address will not be published.