[java] Adding a Scrollable JTextArea (Java)

I am trying to add a scroll bar to a JTextArea. Would someone please tell me what I did wrong with the code below?

JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");

JScrollPane scrollV = new JScrollPane (textArea);
JScrollPane scrollH = new JScrollPane (textArea);

scrollV.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollH.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.setVisible (true);

Thank you in advance.

EDIT: I fixed the code with the Adel Boutros' advice below.

    //FRAME
JFrame frame = new JFrame ("Test");
frame.setSize(500,500);
frame.setResizable(false);
//

//TEXT AREA
JTextArea textArea = new JTextArea("TEST");
textArea.setSize(400,400);    

    textArea.setLineWrap(true);
    textArea.setEditable(false);
    textArea.setVisible(true);

    JScrollPane scroll = new JScrollPane (textArea);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    frame.add(scroll);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This question is related to java swing

The answer is


A scroll pane is a container which contains another component. You can't add your text area to two different scroll panes. The scroll pane takes care of the horizontal and vertical scroll bars.

And if you never add the scroll pane to the frame, it will never be visible.

Read the swing tutorial about scroll panes.


You don't need two JScrollPanes.

Example:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);  

// Add the scroll pane into the content pane
JFrame f = new JFrame();
f.getContentPane().add(sp);

  1. Open design view
  2. Right click to textArea
  3. open surround with option
  4. select "...JScrollPane".