Search code examples
javaswingjscrollpanejtextarea

Java TextArea and JScrollPane


I have searched about attaching a scrollbar to a textarea and found some answers. Tried to fix as it says at suggestions but it still seems not to work. My text area gets longer and longer just, even though I tried to make a static text area.

Wonder what I'm doing wrong here:

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

public class Ovning20 extends JFrame {
    private JPanel p1 = new JPanel();
    private JTextArea ta1;
    JScrollPane scroll;

    public Ovning20()
    {
        setSize(400,200);
        setLocation(500, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        ta1 = new JTextArea();
        ta1.setEditable(true);
        ta1.setBorder(new TitledBorder(new EtchedBorder(), "Skriv in något:"));

        scroll = new JScrollPane(ta1, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        ta1.setAutoscrolls(true);
        ta1.setColumns (20);
        ta1.setRows(3);

        ta1.setLineWrap (true);
        ta1.setWrapStyleWord (true); //default

        p1.add(ta1);
        p1.add(scroll);
        add(p1);
        setVisible(true);
    }

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

Solution

  • Remove the statement

    p1.add(ta1); 
    

    which is adding the textarea to panel p1 and effectively removing it from its scrollpane parent (since components can only have one parent component)