// TLineBreakMeasurer.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.font.*; import java.text.*; import java.awt.geom.*; public class TLineBreakMeasurer extends JFrame { // 1. Constructor public TLineBreakMeasurer(String title) { super(title); setBackground(Color.white); } // 2. The main method... public static void main(String arg[]) { TLineBreakMeasurer frame = new TLineBreakMeasurer("TLineBreakMeasurer"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); frame.getContentPane().add("Center", new DisplayPanel()); frame.pack(); frame.setSize(new Dimension(350,400)); frame.show(); } } // 3. Definition of the display panel class class DisplayPanel extends JPanel { String text = "This is a long string of Java 2D text " + "that can wrap futher to new rows when the " + "user reduces the width of this window!!! " + "So try to reduce the window and see the effect, " + "especially if you have a long word like " + "blablablablablablablablabla."; AttributedString attribString; AttributedCharacterIterator attribCharIterator; public DisplayPanel() { // 4. Prepare the display panel with suitable size and background setBackground(Color.white); setSize(350, 400); // 5. Create the attributed string object using the given text, and // assign a new font and foreground color. attribString = new AttributedString(text); attribString.addAttribute(TextAttribute.FOREGROUND, Color.blue, 0, text.length()); // Start and end indexes. Font font = new Font("sanserif", Font.ITALIC, 20); attribString.addAttribute(TextAttribute.FONT, font, 0, text.length()); } // 6. The paintComponent method... public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; // 7. Retrieve the character iterator from the attributed string attribCharIterator = attribString.getIterator(); // 8. Create a font render contex object and line break measurer. FontRenderContext frc = new FontRenderContext(null, false, false); LineBreakMeasurer lbm = new LineBreakMeasurer(attribCharIterator, frc); // 9. Perform the layout using the line break measurer, and // draw the text on different rows in a 'while' loop. int x = 10, y = 20; // Left and top margins int w = getWidth(), h = getHeight(); // Window dimensions // Leave 15 pixels before the right edge of the the window. float wrappingWidth = w - 15; while (lbm.getPosition() < text.length()) { // Retrieve the text layout for the wrapping width TextLayout layout = lbm.nextLayout(wrappingWidth); // Compute the base line y += layout.getAscent(); // Draw the string from the layout layout.draw(g2, x, y); //Go to the line passing through the acent of characters. y += layout.getDescent() + layout.getLeading(); } } }