Autoscrolling JTextArea + JScrollPane
November 6, 2008 7:32 AM
Subscribe
Java & JTextArea + JScrollpane: How do I autoscroll while text is being appended to the TextArea?
In a project I am working on I have a JTextArea which is used to log operations as they occur. It reports the progress of various operations. The problem is that there are many such operations, so the TextArea fills up and text continues being output to the frame. I would like for that frame to autoscroll while the text is being written to it.
Right now the frame will only scroll to the bottom once all the text has been written to it. Before the text wouldn't even appear before all the operations were done; I fixed that by calling RepaintAll for the jScrollPane. Now I can see the text and I can see it flicker as it updates but the scrollpane stays at the top until the end of all operations. How can I modify this behavior?
I've abstracted this to a small test app. The code is as follows:
package mywork.scrolltest.client;import java.awt.Dimension;import java.awt.Rectangle;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;public class FrmMain extends JFrame { private JTextArea jtaLog = new JTextArea(); private JScrollPane jspLog = new JScrollPane(jtaLog); private JButton jbGo = new JButton(); public FrmMain() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } public static void main (String[] args) { FrmMain frmMain = new FrmMain(); } private void jbInit() throws Exception { this.getContentPane().setLayout( null ); this.setSize(new Dimension(400, 434)); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { this_windowClosing(e); } }); jspLog.setBounds(new Rectangle(10, 10, 375, 340)); jbGo.setText("Go"); jbGo.setBounds(new Rectangle(150, 365, 73, 22)); jbGo.setActionCommand("jbGo"); jbGo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jbGo_actionPerformed(e); } }); jtaLog.setAutoscrolls(true); jspLog.setAutoscrolls(true); this.getContentPane().add(jspLog, null); this.getContentPane().add(jbGo, null); this.setVisible(true); } private void jbGo_actionPerformed(ActionEvent e) { if ("jbGo".equals(e.getActionCommand())) { for (Integer i=0; i<5000; i++) { jtaLog.append("Test string " + i + "\n"); jspLog.paintAll(jspLog.getGraphics()); } } } private void this_windowClosing(WindowEvent e) { System.exit(0); }}
posted by splice to computers & internet (14 comments total)
1 user marked this as a favorite
posted by zeoslap at 7:37 AM on November 6, 2008