JTextArea not working well with JScrollPane inside JPanel

183 views Asked by At

I have been trying to make a JTextArea which I can write in like one would in a Word Document; it wraps around when the texts gets too wide, and scrolls down when it gets too high).
So far, the wrap when it gets too wide works just fine. However, the scroll bar does not work. It does show up, but it does not ever get any longer which means that anything outside of the original dimensions of the JTextArea cannot be viewed no matter what.
Does anyone know what I am doing wrong? Here's how the code looks like; it is the JPanel named panel which I am using later on by adding it to another JPanel which in turn is added to a JFrame.

JTextArea text = new JTextArea(rows, columns);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));
JScrollPane scroll = new JScrollPane(text);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(scroll);
1

There are 1 answers

2
Betlista On BEST ANSWER

Worked fine, when I deleted - text.setPreferredSize

import java.awt.Dimension;
import java.awt.HeadlessException;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

public class ScrollTest extends JFrame {

    public ScrollTest() throws HeadlessException {
        JTextArea text = new JTextArea(5, 20);
        text.setLineWrap(true);
        text.setWrapStyleWord(true);
//      text.setPreferredSize(new Dimension(text.getWidth(), text.getHeight()));

        JScrollPane scroll = new JScrollPane(text);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.add(scroll);

        this.add(panel);

        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new ScrollTest();
    }
}