Skip navigation.
Home

Swings Tips: Auto Scrolling TextArea

Some time it is required that you'r text area scroll down to the last line you've just added to it.


Moreover, TextArea doesn't has a scrollbar by default, it is your job to add scroll bar, then it is also job to make these scroll bars 'auto scroll' when necessary.


this behavior is highly desirable in cases when you're using your TextArea as a logging facility to your program.


Let's go:


first, define your textarea


msgLog = new JTextArea();


Define scrollbar for your textArea


sbrText = new JScrollPane(msgLog);


adjust scrolling policy


sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);


Adjust sizes for scroll and TextArea


  msgLog.setPreferredSize(new Dimension(300,300));
  sbrText.setPreferredSize(new Dimension(400,250));


if you wish, set line warp with true


  msgLog.setLineWrap(true);
  


Now, in your Jframe, add method that enable logging for this frame, let it be printString


int i = 800;
 public void printString(String text){




  msgLog.append(text);
  msgLog.append("\n");
  msgLog.setPreferredSize(new Dimension(400,i+=10)); 
  msgLog.getCaret().setDot( msgLog.getText().length() );
  sbrText.scrollRectToVisible(msgLog.getVisibleRect() );
  


 }


The trick is that eachtime youe add text to the textArea, just resize it to fit the new text, and since it is bounded by scroll bar, so what actully get resizes is the scroll bar, I'm here resizing it by 10 pixels. the variable 'i' is just to maintain the state of the previous size


I'm attaching the code below


I belive that this is not the optimal way to do the job, however as the golden rule in programming say, It just works :)



package mypackage;



import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyFrame extends JFrame{
 
 private JTextArea msgLog;
 private JScrollPane sbrText; // Scroll pane for text area 
 
 public MyFrame() { 
  
  JPanel p = new JPanel();
  msgLog=new JTextArea();
  sbrText = new JScrollPane(msgLog);
  sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  msgLog.setPreferredSize(new Dimension(300,300));
  sbrText.setPreferredSize(new Dimension(400,250));
  msgLog.setLineWrap(true);
  p.add(sbrText);
  getContentPane().add(p, BorderLayout.CENTER);
  
//  Window closure
//  ==============
  addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent e) {
    
   }
  } );
 
 }
 int i = 800;
 public void printString(String text){
  


  msgLog.append(text);
  msgLog.append("\n");
  msgLog.setPreferredSize(new Dimension(400,i+=15));
  msgLog.getCaret().setDot( msgLog.getText().length() );
  sbrText.scrollRectToVisible(msgLog.getVisibleRect() );
  


 }


 public void showWindowCorrect(){
  int maxX=500, maxY=600;
  
//  Get the screen dinmension 
  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  int scrH = (int) screenSize.getHeight();
  int scrW = (int) screenSize.getWidth();
  
//  Set the window's size
  int x = (scrW < maxX ? scrW : maxX);
  int y = (scrH < maxY ? scrH : maxY);
  setSize(new Dimension(x, y));


//  Set other window's attribute
  setResizable(false);
  setLocation((int) (scrW * 0.2), (int) (scrH * 0.1) );
  //setTitle("Credentials Module V2.0");
  
  show();
 }


 public static void main(String [] args)
 {
  MyFrame x = new MyFrame();
  x.showWindowCorrect();
  for(int i=0;i<1000;i++)
  {
   x.printString("hello" + String.valueOf(i));
  // try{Thread.sleep(100);}catch(Exception ex){}
   
  }
 }  


}