problems with scrolling a java TextArea

Posted by Jonathan on Stack Overflow See other posts from Stack Overflow or by Jonathan
Published on 2010-04-12T16:24:51Z Indexed on 2010/04/12 16:43 UTC
Read the original article Hit count: 627

Filed under:
|
|

All,

I am running into an issue using JTextArea and JScrollPane. For some reason the scroll pane appears to not recognize the last line in the document, and will only scroll down to the line before it. The scroll bar does not even change to a state where I can slide it until the lines in the document are two greater than the number of lines the textArea shows (it should happen as soon as it is one greater).

Has anyone run into this before? What would be a good solution (I want to avoid having to add an extra 'blank' line to the end of the document, which I would have to remove every time I add a new line)?

Here is how I instantiate the TextArea and ScrollPane:

JFrame frame = new JFrame("Java Chat Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container pane = frame.getContentPane();
if (!(pane.getLayout() instanceof BorderLayout)) {
    System.err.println("Error: UI Container does not implement BorderLayout.");
    System.exit(-1);
}

textArea = new JTextArea();
    textArea.setPreferredSize(new Dimension(500, 100));
    textArea.setEditable(false);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
JScrollPane scroller = new JScrollPane(textArea);
    scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    pane.add(scroller, BorderLayout.CENTER);

Here is the method I use to add a new line to textArea:

public void println(String a)
{
    textArea.append(" "+a+"\n");
    textArea.setCaretPosition(textArea.getDocument().getLength());
}

Thanks for your help,

Jonathan

EDIT: Also, as a side note, with the current code I have to manually scroll down. I assumed that setCaretPosition(doc.getLength()) in the println(line) method would automatically set the page to the bottom after a line is entered... Should that be the case, or do I need to do something differently?

© Stack Overflow or respective owner

Related posts about java

Related posts about textarea