JTextArea within a JScrollPane

Hi!
I've searched through the Project Swing archive and found lots of questions regarding how you ensure that when text is entered into a JTextArea control (via the append() method) the JScrollPane automatically scrolls to the position where the text was appended.
Unfortunately I haven't yet found a satisfactory solution to this issue.
I have a JTextArea control within a JScrollPane control. I start a seperate thread in order to perform some processing. This operation being run within this thread needs to provide progress information to the user and I present this progress information via the JTextArera control. Although the information is displayed within the JTextArea the JScrollPane unfortunately doesn't scroll down so that the last message entered into the JTextArea is visible. The user needs to scroll down manually in order to see the messages.
I have read that if you invoke JTextArea.setText() or JTextArea.append() from within a thread otherthan the event dispatching thread then the JScrollPane will have no knowledge that text as been added. The article suggested using SwingUtilities.invokeLater(Runnable run) to ensure that the call to JTextArea.setText() or JTextArea.append() is performed within the event dispatching thread. I did create a Runnable class whose sole purpose was to call JTextArea.append() with message information but still the JScrollPane fails to automatically scroll as successive lines of text are being added to the JTextArea control.
Can somebody please shed some light on my problem?

Here's a simple program that works for me. Note, if you comment out the setCaretPosition() method it stops working.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class TestTextArea extends JFrame
     JTextArea textArea;
public TestTextArea()
     JPanel panel = new JPanel();
     setContentPane( panel );
     panel.setPreferredSize( new Dimension( 200, 200 ) );
          textArea = new JTextArea( "one two", 3, 15 );
          JScrollPane scrollPane = new JScrollPane( textArea );
          panel.add( scrollPane );
          JTextArea textArea2= new JTextArea( "abcd", 3, 15 );
          textArea2.setPreferredSize( new Dimension( 50, 10 ) );
          panel.add( textArea2 );
     public void updateTextArea2()
          int line = 0;
          while ( true )
               textArea.append( "\nline: " + ++line );
               textArea.setCaretPosition( textArea.getText().length() );
               try
                    Thread.sleep(1000);
               catch (Exception e) {}
public static void main(String[] args)
TestTextArea frame = new TestTextArea();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
          frame.updateTextArea2();

Similar Messages

  • JTextArea within a JScrollPane within a JSplitPane

    public class CamoDataGUI
         JScrollPane primaryPane;
         JTextArea infoTextArea;
         public CamoDataGUI()
              infoTextArea = new JTextArea("Information", 10,10);
              primaryPane = new JScrollPane(infoTextArea);
         public JScrollPane getContent()
              return primaryPane;
    }Its simply not visible. getContent() is being used to provide one of the values for the SplitPane constructor that asks for an orientation and a left and right component.
    any ideas as to why its MIA?
    Thanks!

    I would like to apologize before anyone responds. I added the wrong class into the constructor of my splitpane.

  • Invisible JTextArea in a JScrollPane

    I want to have an invisible JTextArea in a JScrollPane (i only want a thin border either vieport border or JTextArea border). i tried setOpaque(false) for JTextArea, JScrollPane and both, and it wont work, i dont know why. Could anyone help me?

    This poster is 0 for 3 in responding to previous postings he has made.I did notice - that's why I didn't post the link.
    he/she might now learn how to do a search (for when future questions are ignored)
    What do you think the chances are he'll bother to thank anyone for the help
    he received on this posting?Nil
    a 'thank you' does go a long way to getting the next query answered, but I'd prefer just
    an acknowledement of "it works/doesn't work" - makes it so much easier, when
    searching the forums, when you spot a "yes, that works" at the end.

  • Scrolling of a JTextArea in a JScrollPane

    I have a JTextArea in a JScrollPane.
    It is for a chat and I am constantly appending messages at the bottom of the JTextArea.
    Currently the scrollPanel is scrolling the view so the last line is visible for quite some lines, which is what I want, but from a certain amount of text in the textarea it stops doing that.
    Why does it scroll along at first and then suddenly stops?

    Actually it is a JTextPane instead of JTextArea. My bad.
    And actually it are 2 JTextPanes with a common Document where I am appending the text on (and at the appending I don't have the references to the textpanes).
    Maybe I can add document listeners to the components that have the refs to the textpanes and set the caret position there?

  • Setting JTextArea text within a JScrollPane

    Hey all. I'm attempting to use the setText() method of JTextArea to set the text of various areas located in various scroll panes. The general procedure I'm following is to initialize a new JTextArea and JScrollPane within an initializeGui function, set the properties of the JTextArea, then add it to the scroll pane using .getViewport().add(). After that, a separate function goes through all my form fields loading them with whatever data type is appropriate, in the case of the text areas I'm trying to use setText() to set a string. However, after using setText() the text area is displaying nothing. Here's some code for example (workerPane is using a layout manager exclusive to the environment I'm working in, but I don't believe it's the problem).
    workerLabel = new JLabel("Customer Address:");
              JScrollPane sp = new JScrollPane();          
              JTextArea ta = new JTextArea();          
              //set ta's properties to whatever is needed
              ta.addKeyListener(new java.awt.event.KeyAdapter(){
                   public void keyTyped(KeyEvent e){
                        JTextArea text = (JTextArea)e.getSource();                    
                        String txt = text.getText();                    
                        int nameLength = 240;
                        if ( txt.length() >= nameLength ){
                             text.setText ( txt.substring( 0, nameLength-1 ) );                         
                             Toolkit.getDefaultToolkit().beep();                    
              sp.getViewport().add(ta);          
              workerPane.add("3.1.right.top",workerLabel);
              workerPane.add("3.2.left.center",custAddScrollPane);After each area has been initialized, another function is called to load the data into it. Here are some methods I've tried that haven't worked.
    //basic, but leaves an empty field.
    ta.setText(formProperties[2].getStringValue());
    //this results in two NullPointerException warning windows popping
    ta=(JTextArea)sp.getViewport().getView();
    if(formProperties[2].getStringValue() != null)         ta.setText(formProperties[2].getStringValue());
    sp.getViewport().removeAll();
    sp.getViewport().add(ta);Can anyone point me in the right direction as to how to set my textarea's text?

    I usually use the approach given above. The other option is:
    scrollPane.setViewportView( textArea );

  • Anchoring view to bottom of JTextArea within JScrollPane

    I've got a JTextArea that will be updated asynchronously with text of unknown length. I want the view to move to the bottom every time text is added. I've read through the API for JScrollPane, JScrollBar, JViewports etc. but haven't been able to figure out how to do it. I assume that I have to update the view each time text is added. Here is a summary of the code I've got:
    private JScrollPane historyScroll;
    private JTextArea historyBox;
    public void init(){
        // code removed
        historyBox = new JTextArea();
        historyBox.setLineWrap(true);
        historyBox.setWrapStyleWord(true);
        historyBox.setEditable(false);
        historyScroll = new JScrollPane(historyBox);
        historyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        // code removed
    // add a message to the bottom of the history box
    public synchronized void putMessage(String message){
        historyBox.append(message);
    }

    First, make sure the appending of the text is happening on the swing thread or bad things could result. If it isn't, then use SwingUtilities.invokeLater() when you call the putMessage() method.public void putMessage( String message ) {
         historyBox.append( message );
         // Scroll to the new message
         int height = historyBox.getHeight();
         historyBox.scrollRectToVisible( new Rectangle(0, height, 1, 1) );
    }I'm doing this from memory, so hopefully it is correct. :-)

  • How to repaint a JTextArea inside a JScrollPane

    I am trying to show some messages (during a action event generated process) appending some text into a JTextArea that is inside a JScrollPane, the problem appears when the Scroll starts and the text appended remains hidden until the event is completely dispatched.
    The following code doesnt run correctly.
    ((JTextArea)Destino).append('\n' + Mens);
    Destino.revalidate();
    Destino.paint(Destino.getGraphics());
    I tried also:
    Destino.repaint();
    Thanks a lot in advance

    Correct me if I am wrong but I think you are saying that you are calling a method and the scrollpane won't repaint until the method returns.
    If that is so, you need to use threads in order to achieve the effect you are looking for. Check out the Model-View-Contoller pattern also.

  • Disabling JTextArea in a JScrollPane

    Hello,
    I have an application that contains some JTextFields
    and a JScrollPane with a JTextArea as the viewport.
    The JTextArea is readonly for displaying messages with
    setEnable to false (setEditable and setFocusable are also false).
    The problem is that I can tab thru the fields fine,
    skipping over the scroll pane, however as soon as a
    message is deposited in the scroll pane things
    screw up. What happens is that as I tab
    down to the scroll pane, I loose my cursor and I
    have to tab again to get it back. It is like it gets lost when I try to tab past scroll pane.
    Is it possible that something is being added to the focus
    cycle when I insert a string into the JTextArea?
    Thanks in Advance
    KarlBH

    Also make sure that the JScrollBars are set to not focus.

  • JTextArea in  a JScrollPane autoscrolling chatroom...

    How can I get the JScrollPane to autoscroll and stay at the bottom? It can't be locked at the bottom either because you couldn't scroll up to see what someone had said earlier. Any idea's on this? I'm stumped.

    Sorry, don't have an answer for your latest question, but I was thinking about another of your questions. You only want it to scroll down if it is already at the bottom (like most chat clients). Try:
    JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
    if(scrollBar.getValue() == scrollBar.getMaximum() )
        scrollBar.setValue( scrollBar.getMaximum() );Except that won't work because you'll have already added a line, and the scrollbar won't be at maximum. You could introduce a window, ie, if the scrollbar value is within 5 of the maximum, keep scrolling down.... but if someone sends a message longer than 5 lines, you're screwed....
    Seemed like a good idea to begin with, but I think it introduces more problems.
    Maybe you'll find it useful anyway.
    Good luck,
    Radish21

  • Determining the visible lines of a JEditorPane within a JScrollPane

    I need to track what lines are visible (the Document line numbers) within the Viewport of a JScrollPane that contains a JEditorPane. Is this achievable?

    That's a tricky one.
    Maybe something like this:
    First get the view coordinate of the top left corner of the view port
    Point p = scrollPane.getViewPort().getViewPosition();Then convert that view location into a model location. The model location will be an index into the document.
    int modelLocation = editorPane.viewToModel( p );Now you just need to count how many lines are before this index location. As I recall there is a main root element for the whole document. The root element is made up of child elements, one for each line. This may be different for HTML but might work for text or rich text.
    Element rootElement = editorPane.getDocument().getRootElements()[0];
    // getElementIndex() will give you the child element index (e.g. line element that is at the given document location).
    int lines = rootElement.getElementIndex( modelLocation );Do the same for the point location that is at the viewport's location plus the viewport's size (i.e. the lower right corner of the viewport).
    There is a LOT of speculation here since I haven't actually put this to a test case. But maybe its enough to point you in a direction that works.
    -Mike

  • Unable to grow and shrink a JTable within a JScrollPane

    I need help with the following: I want to display a JTable component with a calendar like design. Dragging the size of the parent component (having a border to drag) should dynamically adapt the JTable' size and its cells. Since the JTable has a minimum size shrinking the parent component should show scrollbars if the minimum size is reached horizontal or vertical respectively.
    I have the JTable put ijnto the viewport of a scrollpane and the scrollpane is the child component of a JPanel. So dragging appears with the panel.
    The JTable cells do nicely but from a specific size on there is a grey area on the lower part of the JPanel which is not repainted. What is causing this? What do I have to do? I'm lost in the jungle of invalidate(), repaint(), update(), doLayout() etc.
    Here is my SSCCE (at least I hope it is one):
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    //public class MyComponent extends JScrollPane
    public class MyComponent extends JPanel
    ///   class data
         static public final long serialVersionUID = -1L;
         static public final int c_ColWidth = 29;
         static public final int c_RowHeight = 18;
         static public final int c_TableWidth = 930;
         static public final int c_TableHeight = 234;
    ///   instance data
         private String[] m_strColHeader = {
              "01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
              "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
              "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",
              "31",
         private Object[][] m_Data = new Object[12][33];// data array
         private TableModel m_DataModel = new AbstractTableModel() {
              static public final long serialVersionUID = -1L;
              public int getColumnCount() { return m_strColHeader.length; }
              public int getRowCount() { return m_Data != null ? m_Data.length : 0; }
              public Object getValueAt(int row, int col) { return m_Data[row][col]; }
              public String getColumnName(int col) { return m_strColHeader[col]; }
              public Class getColumnClass(int col) { return String.class; }
              public boolean isCellEditable(int row, int col) { return false; }
              public void setValueAt(Object aValue, int row, int col) {
                   m_Data[row][col] = aValue;
         protected BorderLayout myLayout = new BorderLayout();
         protected JTable tableView = new JTable(m_DataModel);
         protected JScrollPane scrollPane = new JScrollPane(tableView);
    ///   public class methods
         static public void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch(Exception e)
                   e.printStackTrace();
              MyComponent comp1 = new MyComponent();
              JFrame frame = new JFrame("MyComponent");
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.getContentPane().add(comp1);
              frame.pack();
              frame.setVisible(true);
    ///   constructors
         public MyComponent()
              try
                   jbInit();
                   initTable();
              catch(Exception ex)
                   ex.printStackTrace();
    ///   protected instance methods
         protected void initTable()
              // do nor allow user interaction with calendar view
              tableView.getTableHeader().setReorderingAllowed(false);
              tableView.getTableHeader().setResizingAllowed(false);
              //tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tableView.setRowHeight(c_RowHeight);
              // adapt all CellRenderers
              for (int i = 0; i < m_DataModel.getColumnCount(); i++)
                   TableColumn column = tableView.getColumn(tableView.getColumnName(i));
                   column.setMinWidth(c_ColWidth);
                   column.setPreferredWidth(c_ColWidth);
    ///   private instance methods
         private void jbInit() throws Exception
              this.setLayout(myLayout);
              this.add(scrollPane, BorderLayout.CENTER);
              scrollPane.getViewport().setMinimumSize(new Dimension(c_TableWidth, c_TableHeight));
              scrollPane.getViewport().setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              tableView.setPreferredSize(new Dimension(c_TableWidth, c_TableHeight));
              addComponentListener(new MyComponent_componentAdapter(this));
    ///   event handling
         public void componentBoundsChanged(ComponentEvent e)
              scrollPane.setBounds(0, 0, getWidth(), getHeight());
              scrollPane.getViewport().setBounds(0, 0, getWidth(), getHeight());
              //tableView.setBounds(0, 0, getWidth(), getHeight());
              tableView.setSize(scrollPane.getViewport().getWidth(), scrollPane.getViewport().getHeight());
              tableView.setRowHeight(getBounds().height / 13 < c_RowHeight ?
                        c_RowHeight : getBounds().height / 13);
              System.out.println("componentBoundsChanged: getBounds() = " + getBounds());
              System.out.println("componentBoundsChanged: getSize() = " + getSize());
              System.out.println("componentBoundsChanged: getViewport().getBounds() = " + scrollPane.getViewport().getBounds());
              System.out.println("componentBoundsChanged: getViewport().getSize() = " + scrollPane.getViewport().getSize());
              System.out.println("componentBoundsChanged: tableView.getBounds() = " + tableView.getBounds());
              System.out.println("componentBoundsChanged: tableView.getSize() = " + tableView.getSize());
    ///   event adapters
    class MyComponent_componentAdapter extends ComponentAdapter
         protected MyComponent adaptee;
         MyComponent_componentAdapter(MyComponent adaptee)
              this.adaptee = adaptee;
         public void componentMoved(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
         public void componentResized(ComponentEvent e)
              adaptee.componentBoundsChanged(e);
    }

    I guess i am facing exactly opposite problem.
    What i want to do is, I have nested tables in a scroll pane. So I don't want a scroll pane to show exactly whatever visible rows are there in Table (No extra space). If i expand any row, i want scroll pane to be able to show expanded.

  • My JScrollPane scrollbar defaults to the bottom not top

    Hi,
    I have a slight problem with a JScrollPane in that it appears to default the scrollbar to the bottom when the scrollbar is visible. I basically have a panel on a JFrame containing a JTextArea within a JScrollPane.
    Does anyone know how I can make it default to the top ? I think I found a method that works on JScrollBar but can't seem to find one for JScrollPane.
    Thanks,
    Andy

    I've just tried this and it works great, thanks for that.
    I was looking for methods in JScrollPane to control the bar, never thought of the JTextArea class having the answer

  • JScrollPane with JTextArea

    I'm creating a program where a user enters a string into a JTextField and then that string is appended to a new line in a JTextArea that is inside of a JScrollPane. I wanted to know how I could make it so that each time a line is appended to the JTextArea that the JScrollPane scrolls down to the bottom left, showing the new line? (If i don't touch the JScrollPane, this works on its own but after I scroll around it doesnt update the view to the bottom anymore).
    Thanks,
    swing can be a bit confusing at times.

    http://java.sun.com/docs/books/tutorialJWS/uiswing/components/ex6/TextDemo.jnlp
    http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html

  • JScrollPane w/ JTextArea problems

    I've written a simple terminal for a project I'm working on, with a JTextField for inputs and a JTextArea to display outputs. The JTextArea uses a JScrollPane to let it scroll vertically, and wraps text to avoid horizontal scrolling.
    My problem is this: when I append text to the text area, the scroll pane sometimes scrolls to the bottom, sometimes scrolls part-way, and sometimes doesn't move at all. Ideally, I'd like to have the scroll pane always pushed to the bottom. Does anyone know what causes this kind of behaviour? What input causes the bar to scroll, and what input doesn't?
    thanks,
    Andrew

    I don't know what causes the kind if behaviour you described, but this is how you get the scrollPane to scroll to the bottom:
    int bottom = scrollPane.getVerticalScrollBar().getMaximum();
    scrollPane.getVerticalScrollBar().setValue(bottom);

  • JScrollPane is not making my JTextArea scrollable....

    I'm making a little chat client for school and I'm having trouble getting my GUI to work right. I'm basically having two problems:
    1. When I put my JTextArea's in JScrollPane's, they aren't becoming scrollable. When I type on it the text just goes off the JTextArea and doesn't scroll. I can't understand why.
    2. When I don't specify a preferred size for my JTextArea's they shrink up to as small as possible and are unusable. When I do specify one they don't stretch if I increase or decrease the size of the window. I basically want them to use up as much space as possible.
    Here's my code:
    package main;
    import javax.swing.*;
    import java.awt.*;
    public class Main {
         private JFrame frame;
         private JPanel panel,output,input;
         private JTextArea area,field;
         private JButton button;
         public Main(){
              frame = new JFrame("Chat Window");
              panel = new JPanel();
              output = new JPanel();
              input = new JPanel();
              area = new JTextArea();
              field = new JTextArea();
              button = new JButton("Send");
              button.setSize(50,20);
              //area.setPreferredSize(new Dimension(300,300));
              //field.setPreferredSize(new Dimension(240,100));
              output.add(new JScrollPane(area),"Center");
              input.add(new JScrollPane(field),"West");
              input.add(button,"East");
              panel.add(new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,output,input));
              frame.add(panel);
              frame.setSize(300,450);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setResizable(true);
              frame.setVisible(true);
         public static void main(String...a){
              Main main = new Main();
    }

    How about something like this?:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    public class Main
        private JFrame frame3;
        private JPanel outputPnl, inputPnl;
        private JTextArea outputTxt, inputTxt;
        private JButton btn3;
        private void wtf3()
            frame3 = new JFrame();
            outputTxt = new JTextArea();
            inputTxt = new JTextArea();
            btn3 = new JButton("Send");
            outputPnl = new JPanel();
            inputPnl = new JPanel();
            outputPnl.setLayout(new GridLayout());
            outputPnl.add(new JScrollPane(outputTxt));
            inputPnl.setLayout(new BorderLayout());
            inputPnl.add(new JScrollPane(inputTxt), BorderLayout.CENTER);
            JPanel btnPanel = new JPanel();
            btnPanel.add(btn3, BorderLayout.CENTER);
            btnPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            inputPnl.add(btnPanel, BorderLayout.EAST);
            JSplitPane splitP3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, outputPnl, inputPnl);
            frame3.getContentPane().add(splitP3);
            frame3.setSize(600, 450);
            frame3.setLocationRelativeTo(null);
            frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame3.setVisible(true);
            splitP3.setDividerLocation(0.8);       
        public Main()
            wtf3();
        private static void createAndShow()
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    Main mn = new Main();
        public static void main(String[] args)
            createAndShow();
    }

Maybe you are looking for