Java AWT TextLayout layout multiple lines of text

Description

Java AWT TextLayout layout multiple lines of text

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  Random rnd = new Random();

  @Override//from   ww w  .j a v  a2 s . c om
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;
    g2d.setBackground(Color.WHITE);
    g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight());
    // antialising
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // Serif bold 
    Font serif = new Font("Serif", Font.BOLD, 22);
    g2d.setFont(serif);
    String latinText = "Lorem ipsum dolor sit amet, consectetur "
        + "adipiscing elit, sed do eiusmod tempor incididunt ut "
        + "labore et dolore magna aliqua. Ut enim ad minim veniam, "
        + "quis nostrud exercitation ullamco laboris nisi ut aliquip "
        + "ex ea commodo consequat. Duis aute irure dolor in "
        + "reprehenderit in voluptate velit esse cillum dolore eu "
        + "fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
        + "non proident, sunt in culpa qui officia deserunt mollit "
        + "anim id est laborum.";
    
    AttributedString attrStr = new AttributedString(latinText);
    attrStr.addAttribute(TextAttribute.FONT, serif);
    AttributedCharacterIterator attrCharIter = attrStr.getIterator();
    FontRenderContext fontRenderCtx = g2d.getFontRenderContext();
    LineBreakMeasurer lineBreakMeasurer = 
            new LineBreakMeasurer(attrCharIter, fontRenderCtx);
    float wrapWidth = getParent().getWidth();
    float x = 0;
    float y = 0;
    while (lineBreakMeasurer.getPosition() < attrCharIter.getEndIndex()) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(wrapWidth);
        y += textLayout.getAscent();
        textLayout.draw(g2d, x, y);
        y += textLayout.getDescent() + textLayout.getLeading();
    }
  }

  public static void main(String[] args) {
    // create frame for Main
    JFrame frame = new JFrame("java2s.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Main Main = new Main();
    frame.add(Main);
    frame.setSize(300, 210);
    frame.setVisible(true);
  }
}



PreviousNext

Related