Jump to content
  • Advertisement


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


Java: JTextPane within a JScrollPane

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

If you intended to correct an error in the post then please contact us.

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 this post

Link to post
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();

// 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


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!

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!