Search code examples
javaswingjscrollpanejtextareapreferredsize

JScrollPane doesn't work


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??


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.