I am using JTextArea in JScrollPane
I want to limit the maximum number of possible lines and the maximum characters in each line.
I need the line to be exactly the same as on the screen, each line ends with "\ n" (if there is another line after it), and the user can insert only X lines and Y characters in each line.
I tried to limit the lines, but I do not know exactly how many lines I have due to line breaks. Linear packaging starts visually visually on the screen (due to the width of the JTextArea), but the line of the component is really the same line for which '\ n' is not specified to indicate a new line. I do not know how to limit the maximum characters in each line as I type.
There are 2 steps:
- Having typed a line, make sure that the user cannot type more lines X and Y in each line. (even if the line break is only visual or the user typed "/ n")
- Insert a line in DB - after clicking “OK”, it converts a line in which each line ends with “/ n”, even if the user did not type it and the line was wrapped only visually.
There are several problems if I count the characters in a line and insert '/ n' at the end of the line, which is why I decided to do this in two steps. At the first stage, the user prints the ehile, I would prefer to limit it to visual and force wrpping lines or something like that. Only in the second stage, when I save the line, will I add '/ n', even if the user did not type it at the end of the lines!
Anyone have an idea?
I know that I will have to use DocumentFilter OR StyledDocument.
Here is an example code that restricts only strings to 3: (but not characters in a string to 19)
private JTextArea textArea ; textArea = new JTextArea(3,19); textArea .setLineWrap(true); textArea .setDocument(new LimitedStyledDocument(3)); JScrollPane scrollPane = new JScrollPane(textArea public class LimitedStyledDocument extends DefaultStyledDocument /** Field maxCharacters */ int maxLines; public LimitedStyledDocument(int maxLines) { maxCharacters = maxLines; } public void insertString(int offs, String str, AttributeSet attribute) throws BadLocationException { Element root = this.getDefaultRootElement(); int lineCount = getLineCount(str); if (lineCount + root.getElementCount() <= maxLines){ super.insertString(offs, str, attribute); } else { Toolkit.getDefaultToolkit().beep(); } } private int getLineCount(String str){ String tempStr = new String(str); int index; int lineCount = 0; while (tempStr.length() > 0){ index = tempStr.indexOf("\n"); if(index != -1){ lineCount++; tempStr = tempStr.substring(index+1); } else{ break; } } return lineCount; } }
Billbo bug
source share