S.Srihari S.Srihari - 1 month ago 20
Java Question

JScrollPane is not added to JTextArea

I saw a few questions like this question, but I couldn't get this solved. I cannot get a

JScrollPane
visible on
JTextArea
. Can anyone please point out where I have done my mistake? Thanks.

package experiement;

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Experiment extends JFrame{

public Experiment(){
JTextArea tarea=new JTextArea();
tarea.setBounds(100,100,200,200);
JScrollPane pan= new JScrollPane();
pan.setPreferredSize(new Dimension(100,100));
pan=new JScrollPane(tarea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

add(pan);
add(tarea);

setLayout(null);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[]aegs){
Experiment e=new Experiment();
}
}

Answer

When you use JTextArea component with JSrcollPane component you should set size and position to the last component and not to the first one, and when you add the created elements to the JFrame you should only add JScrollPane component because it is considered as container to the JTextArea component, try this code:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends JFrame
{
    JTextArea tarea;
    JScrollPane pan;
    public Main()
    {
        tarea = new JTextArea();
        pan = new JScrollPane(tarea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        pan.setBounds(100, 100, 200, 200);

        add(pan);

        setLayout(null);
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] aegs)
    {
        Main f = new Main();
    }
}