problems with scrolling a java TextArea
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 t开发者_如何学JAVAhe 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?
The problem is textArea.setPreferredSize(new Dimension(500, 100));
Remove that. Set the perferredSize of the scrollpane or the size of your frame instead
Is this a solution? I didn't test it, so please don't kill me.
scroller.getVerticalScrollBar().setValue(pane.getVerticalScrollBar().getMaximum());
精彩评论