Search code examples
javaswingjscrollpanejtextareacaret

How to auto-scroll when text is added to my JScrollPane/JArea?


I have a JTextArea in a small app that shows all the exceptions e.getMessage and other things. However, the JScrollPane does not show the latest results. I have to manually scroll it so that I could see what has just happened.

I want it to be exactly like Eclipse Console

How can I set up the cursor ?

Here is my code

publiv void createGUI)( {

                JTextArea progress = new JTextArea("");

        JScrollPane jsp = new JScrollPane(progress);
        jsp.setBounds(320, 10, 280, 300); 
        j.add(jsp) ;

        JScrollBar max = jsp.getVerticalScrollBar() ;
        max.setValue(max.getMaximum() ) ;        // I tried this as suggested by Yasmani Llanes, but it did not work
...

Solution

  • Try setting the caret position at the end of the text:

    progress.setCaretPosition(progress.getText().length()) 
    

    The following example works for me:

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    
    
    public class Test extends JFrame {
        private JTextArea txtTest;
    
        Test() {
            this.setSize(500, 300);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLayout(new BorderLayout());
    
            JScrollPane pane = new JScrollPane();
            txtTest = new JTextArea();
            pane.setViewportView(txtTest);
            this.add(pane, BorderLayout.CENTER);
    
            JButton btnAddText = new JButton("Add Text");
            btnAddText.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    txtTest.setText(txtTest.getText() + "\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sagittis id nibh vel rhoncus. ");
    
                    String text = txtTest.getText();
    
                    txtTest.setCaretPosition(text != null ? text.length() : 0);
                }
            });
            this.add(btnAddText, BorderLayout.SOUTH);
    
            this.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Test();             
                }
            });
        }
    }