简体   繁体   中英

JTextArea with JScrollPane isn't scrolling once full

I'm trying to make my JTextArea scrollable when it fills up with text but when I add a JScrollPane it just adds a scrollbar that doesn't do anything. When I add more text than my JTextArea can display it doesn't change and doesn't append any more text.

    Container window = getContentPane();
    window.setLayout(new FlowLayout());

    display = new JTextArea(TEXT_AREA_ROWS, TEXT_AREA_COLUMNS);
    display.setLineWrap(true);
    display.setPreferredSize(TEXT_AREA_DIMENSIONS);
    display.setBackground(TEXT_BG_COLOR);
    display.setForeground(TEXT_COLOR);
    display.setEditable(false);
    display.setFont(TEXT_FONT);
    window.add(display);

    scroll = new JScrollPane(display);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    scroll.setPreferredSize(display.getPreferredSize());
    window.add(scroll);

Thanks in Advance

EDIT: Realised my mistake, I was setting the preferred size of the textArea instead of the scrollPane. This is solved by removing display.setPreferredSize(TEXT_AREA_DIMENSIONS); and adding a scroll.setPreferredSize(new Dimension(width, height)); Silly me.

but if you append text to it with display.append(string) then the text gets added to the bottom which may or not be on screen at the time.

Well, you didn't state that you were using the append(...) method in your original question. That is why you should always post a proper SSCCE that demonstrates the problem so we don't have to guess what you are doing.

See Text Area Scrolling for the probable problem and a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM