[an error occurred while processing this directive]

Break a Line for text layout


In this section, we are providing you an example to break a line. To break down the text into lines, the class LineBreakMeasurer is used. The class Hashtable maps keys to values.

A string is defined in the constructor of class AttributedString which holds the text. To allows iteration through text information, the class AttributedCharacterIterator is used. The method getIterator() creates an instance of AttributedCharacterIterator which provides access to the string. The method attributedCharacterIterator.getBeginIndex() starts the text and the method attributedCharacterIterator.getEndIndex() ends the text.

The method setPosition() sets the current position of the LineBreakMeasurer. The getPosition() returns the current position of LineBreakMeasurer. The method getAscent() and getDescent() of class TextLayout returns the ascent and descent of TextLayout respectively. The method getLeading() returns the leading of TextLayout.

Following code draws the TextLayout at (X, Y).

textLayout.draw(graphics2D, X, Y);

Here is the code of LineBreakExample.java 

import java.awt.*;
import java.text.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.font.*;
import java.util.Hashtable;

public class LineBreakExample extends JPanel {
  private LineBreakMeasurer lineBreakMeasurer;
 private int start, end;
  private static Hashtable hash = new Hashtable();
  private static AttributedString attributedString = new AttributedString(
       "Java is an Object Oriented Programming Language which has "
      " an extensive class library available in the core language packages.
    Java "
"was designed with networking in mind and comes with many classes "
    +" to develop sophisticated Internet communications. ",
  public LineBreakExample() {
    AttributedCharacterIterator attributedCharacterIterator = 

    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();
    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
     new FontRenderContext(null, false, false));
  public void paintComponent(Graphics g) {
  Graphics2D graphics2D = (Graphics2D) g;
    Dimension size = getSize();
    float width = (float) size.width;
  float  X, Y = 0;
    while (lineBreakMeasurer.getPosition() < end) {
    TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
    Y += textLayout.getAscent();
    X = 0;
    textLayout.draw(graphics2D, X, Y);
  Y += textLayout.getDescent() + textLayout.getLeading();
  public static void main(String[] args) {
    JFrame frame = new JFrame("Show Line Break");
    LineBreakExample controller = new LineBreakExample();
    frame.setSize(new Dimension(200200));

Output will be displayed as:

Download source code


[an error occurred while processing this directive]