Skip to main content

Limiting JTextArea

2 replies [Last post]
Joined: 2004-06-02

Basically all I want to do is limit a JTextArea to, say, four lines max. I mean 4 physical lines, not 4 sentences. Now I know about PlainDocument and I know how to determine how many carriage returns there are in the JTextArea. But sometimes there will be carriage returns and sometimes there will just be linewraps at a word space. Both create "new lines" in my situation.

So I'm struggling determining how many lines are in the JTextArea when carriage returns aren't used and how to limit the max number of lines. I have got as far as stopping entry when the fourth line is at its maximum width but this also stops entry on previous lines if the user moves the cursor back up a line.

At this point I'm going around in circles and need a fresh approach. Any code examples or thoughts would be sincerely appreciated.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2003-06-13

Here is another hacky idea.

Ask the JTextArea for its preferredSize when it starts up with just one or two characters in it; and by doing that deduce its preferredSize when it is 4 lines height.

Add a new document which extends from something like PlainDocument and give the maximum height as well as the JTextArea to that new document.
The document can then accept or reject characters that would make the preferredHeight get too large.

Its really a hack, but I believe it would work.

Joined: 2008-03-19

The straight way is too long and complex since much of required classes and
methods are not public or protected. I could suggest only a workaround: calculate the location (JTextComponent.modelToView) of the last document position and then a number of the last soft line using Y and height values of the location.