Tuesday 14 August 2012

Read line (or get line count) from JTextArea with wrap enabled

public class Demo {
     JTextArea textArea = new JTextArea(text, 5, 50);
     textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
     textArea.setEditable(false);
     textArea.setLineWrap(true);
     textArea.setWrapStyleWord(true);

     private static String[] readLinesFromTextArea(JTextArea textArea, int limitRows) {
           String content = textArea.getText();
           String[] lines = new String[limitRows];
           Arrays.fill(lines, "");
           try {
              int count = 0;
              int offs = 0;
              while (offs < content.length() && count < limitRows ) {
                 int end = Utilities.getRowEnd(textArea, offs);
                 String line = StringUtils.substring(content, offs, end);
                 lines[count++] = line;
                 offs = end + 1;
              }
           } catch (BadLocationException e) {
             log.error("Read line from 'Other' text area failed. Cause:\n", Throwables.getStackTraceAsString(e));
        }

        return lines;
    }
}

No comments:

Post a Comment