Drawing a paragraph of text in Swing


import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
public class Main extends JFrame {
   private String text;
   LineBreakMeasurer lineMeasurer;
   int beginIndex, endIndex;
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
      text = "It is, in fact, nothing short of a miracle that the modern methods " +
             "of instruction have not yet entirely strangled the holy curiosity " +
             "of inquiry; for this delicate little plant, aside from stimulation, " +
             "stands mainly in need of freedom; without this it goes to wrack and " +
             "ruin without fail. It is a very grave mistake to think that the " +
             "enjoyment of seeing and searching can promoted by means of coercion " +
             "and sense of duty. To the contrary, I believe that it would be " +
             "possible to rob even a healthy beast of prey of its voraciousness, " +
             "if it were possible, with the aid of a whip, to force the beast to " +
             "devour continuously, even when not hungry,especiallyif the food, " +
             "handed out under such coercion, were to be selected accordingly." +
             "n" +
             "Albert Einstein";
      AttributedString as = new AttributedString(text);
      AttributedCharacterIterator aci = as.getIterator();
      FontRenderContext frc = new FontRenderContext(null, false, false);
      beginIndex = aci.getBeginIndex();
      endIndex = aci.getEndIndex();
      // Create a new LineBreakMeasurer from the paragraph.
      lineMeasurer = new LineBreakMeasurer(aci, frc);
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
      Dimension size = getSize();
      float width = (float) size.width - 40;
      float x=10, y=30;
      g2d.setFont(new Font("Serif", Font.PLAIN, 24));
      while (lineMeasurer.getPosition() < endIndex) {
         TextLayout layout = lineMeasurer.nextLayout(width);
         x = 10;   
         y += layout.getAscent() + layout.getDescent() + layout.getLeading();
         layout.draw(g2d, x, y);
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(420, 230);