• ### What is your GameDev Story?

Public Group

#### Archived

This topic is now archived and is closed to further replies.

# Java: JTextPane within a JScrollPane

This topic is 5400 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, since JTextPane doesn''t come with its own append method, I just wrote some method to append text to a JTextPane within a GUI I made. The JTextPane is part of a JScrollPane, the problem is that when I append text to my JTextPane, I want the vertical scrollbar to automatically slide down to the last line of text. What I did so far was to set the JTextPane''s caret position to the last character, and this works. The problem is that first the caret moves to the top of the JTextPane, stays there for a split second, and then moves to the end. This causes a lot of really annoying flicker.
  public void append(String newText) {
contents.setText(contents.getText() + newText);
contents.setCaretPosition(contents.getCaretPosition() + newText.length());
}

So my question is: is there a better way to get the scroll bar to automatically scroll to the end of the JTextPane that does not result in any flickering? Thanks.

##### Share on other sites
I''m no Java expert, but I just recently had to solve a similar problem and found that JTextArea and JScrollPane were what I needed - just put a JTextArea on a JScrollPane, and it works like a charm. Plus the JTextArea has it''s own append method, so you don''t have to write it.

		// grab the main pane		Container window = getContentPane();		//1337 h4}{0|2 font!		Font myFont = new Font("Courier New", Font.PLAIN, 14);		// create our text area (this will look cool too		longOutput = new JTextArea();		longOutput.setForeground(Color.green);		longOutput.setBackground(Color.black);		longOutput.setFont(myFont);		longOutput.setEditable(false);		// create scrollabe pane		// put together bottom pane		JScrollPane bottom = new JScrollPane(longOutput);		// sets up the grid for our top and bottom		window.setLayout(new GridLayout(2,1));		// put together main pane		window.add(bottom);

That''s part of my source, slightly edited to be more general, of course you need to know a little bit about panes and panels.

Good luck!

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

(You must login to your GameDev.net account.)

• 15
• 10
• 9
• 35
• 16
• ### Forum Statistics

• Total Topics
634125
• Total Posts
3015679
×