What is the Graphics.drawChars() method in Java?

Overview

The drawChars() method is used to draw the given list of characters. This method is provided by the Graphics class in the awt package.

It will draw the characters with present graphics, context color, and font.

Syntax

graphics.drawChars(data, offset, length, x, y)

Parameters

The drawChars method accepts the following parameters:

  • data: This parameter accepts an array of characters to be drawn.
  • offset: This provides an index of the character from which we want to start drawing the characters.
  • length: This provides the length of the characters to be drawn.
  • x: This provides the x coordinate from where we want to start drawing the text.
  • y: This provides the y coordinate from where we want to start drawing the text.

Example

Let’s take a look at an example:

//import required packages
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

  public void paint(Graphics g) {

      //provide character array
      char [] chararray = {'H', 'e', 'l', 'l', 'o', ' ', 'f', 'r', 'o', 'm', ' ', 'E', 'd', 'u','c', 'a','t','i','v','e'};

      //draw array of characters
      g.drawChars (chararray, 0, chararray.length, 10, 50);
  }

  //main method
  public static void main(String[] args) {
    //Instantiate JFrame
    JFrame frame = new JFrame();

    //add panel
    frame.getContentPane().add(new Main());

    //Will exit the program when you close the gui
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //set width and height of the frame
    frame.setSize(400,400);

    //set visibility of the frame
    frame.setVisible(true);
  }
}
  

Explanation

In the above code:

  • Line 11: We declare and initialize an array of characters chararray.
  • Line 14: We draw characters by calling the drawChars() method on graphics object. And we pass the parameters character array as chararray, offset as 0, character length as chararray.length, x coordinate as 10, and y coordinate as 50.

The output is displayed as Hello from Educative.

Free Resources