title: JTextArea: Limit string width and line count?
body: <p>The user needs to enter text to be printed on a fixed-size label. Given a font, the label has a fixed number of lines and also a fixed width in pixels. How can I adapt a JTextArea (or something else in Swing, if there is another option) to this use case?</p>
  
  <ul>
  <li>Maximum number of lines</li>
  <li>Each line of characters not exceeding a certain pixel width</li>
  <li>Text wrapping from line to line at the word level for lines attempting to exceed the maximum pixel width</li>
  </ul>
  
  <p>I have a PlainDocument that limits the length of a single line of text according to the width in pixels of the string, measured in capital Ws (the widest character in my font):</p>
  
  <pre><code>public class StandardDocument extends PlainDocument {
  
      /****** VARIABLES **********************************************/
      public boolean upperCase = true;
      private int textLimit;
      private int textWidth;
      private int fieldWidth;
      private JTextField textField = new JTextField();
  
  
      /** Get the maximum width of this text field, measured in capital Ws.
       *  @return textWidth - int
       **/
      public int getTextWidth() {
          return textWidth;
      }
  
      /** Get the maximum width of this text field, measured in pixels.
       *  @return textWidth - int
       **/
      protected int getFieldWidth() {
          return fieldWidth;
      }
  
      /** Core method for inserting value provided by user after "cleaning" user's value automatically. **/
      public void insertString(int offs, String str, AttributeSet attr) throws BadLocationException {
  
          if (str == null) { return; }
  
         // Set field value when value is within character limit of field.
          if (textWidth &gt; 0) {
              int attemptedWidth = textField.getFontMetrics(Constants.defaultFontLabels).stringWidth(getText(0, getLength()) + str);
              if (attemptedWidth &gt; fieldWidth) {
                  return;
              }
          }
  
           // Set value in field.
          super.insertString(offs, str, attr);
      }
  
      /** Set the maximum text width as a maximum number of capital Ws this field may hold. **/
      public void setTextWidth(int wLimit) {
          if (wLimit &gt;= 0) {
              textWidth = wLimit;
              StringBuffer outputBuffer = new StringBuffer(wLimit);
              for (int i = 0; i &lt; wLimit; i++){
                 outputBuffer.append("W");
              }
              fieldWidth = textField.getFontMetrics(Constants.defaultFontLabels).stringWidth(outputBuffer.toString());
          }
      }
  }
  </code></pre>