Question

My JScrollPane is around JTextArea:

    ...
    errorText = new JTextArea();
    errorText.setLineWrap(true);
    errorText.setWrapStyleWord(true);
    errorText.setPreferredSize(new Dimension(300, 150));

    JScrollPane scrollPane = new JScrollPane(errorText);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setBorder(BorderFactory.createTitledBorder("Info Area"));
    ...

and code, that adds text to errorText:

public void setText(String mes) {
    e140TEST2.errorText.append(lineNum + ".   " + mes + "\n");
    lineNum++;
}

after adding some num of lines (when text have more height, than JTextArea), JScrollPane doesn't work (text isn't scrooling). What it can be??

Was it helpful?

Solution

errorText.setPreferredSize(new Dimension(300, 150));

Don't hardcode the preferred size of the text area (or any component). The preferred size changes as you add/remove text.

Instead create your text area like:

textArea = new JTextArea(5, 30);

to provide an initial size.

OTHER TIPS

Although not the ideal solution, you can still set a preferred size in pixels and retain scrolling capabilities if you use a JTextPane instance instead of a JTextArea one. Plus, JTextPane automatically wraps lines and does so at word boundaries (which is what you seem to be after). Try the following SSCCE:

import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;

public class PaneWithScroll {
    public static void main (String[] args) {
        JTextPane errorText = new JTextPane();
        //errorText.setLineWrap(true);       
        //errorText.setWrapStyleWord(true);         
        errorText.setPreferredSize(new Dimension(300, 150));

        JScrollPane scrollPane = new JScrollPane (errorText);
        scrollPane.setVerticalScrollBarPolicy 
                          (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        scrollPane.setBorder (BorderFactory.createTitledBorder("Info Area"));

        JFrame frame = new JFrame();
        frame.add (scrollPane);
        frame.pack();
        frame.setVisible (true);
    }
}

I should add that this may serve as a quick patch. However, best practices dictate that you should always try to decouple potentially platform-dependent specifications from your GUI design. In this case, absolute dimensions.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top