7

I'm trying to add a Vertical scrolling my java programs textarea. I am using this code to create my JScrollPane:

console = my textarea.

I am also Declaring JScrollPane vertical;

        vertical = new JScrollPane(console);
    vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    vertical.setVisible(true);
    this.add(vertical);

EDIT:

View of program:

enter image description here I'm new to Java but shouldn't that work and add a Vertical scroll bar to my textarea

What am I doing wrong?

Thanks for any help.

Duncan Palmer
  • 2,865
  • 11
  • 63
  • 91

3 Answers3

10

Here is an example:

enter image description here

import java.awt.Dimension;
import javax.swing.*;

public class ScrolledPane extends JPanel
{
    private JScrollPane vertical;
    private JTextArea console;

    public ScrolledPane()
    {
        setPreferredSize(new Dimension(200, 250));
        console = new JTextArea(15, 15);

        vertical = new JScrollPane(console);
        vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        add(vertical);
    }


    public static void main( String args[] )
    {
        new JFrame()
        {{
            getContentPane().add(new ScrolledPane());
            pack();
            setVisible(true);
        }};
    }
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 1
    please amend that new JTextArea(int, int);, then is definitions for PreferredSize use-less +1 – mKorbel Oct 14 '11 at 11:59
  • Thanks for the great example it works now, but for some reason it is always in the middle of the window, shown here - http://screensnapr.com/v/LnRvql.png is there any way I can set a custom location? – Duncan Palmer Oct 14 '11 at 12:12
8

I think that in official tutorial about JTextArea and JScrollPane is described everything about that, another examples here and here

mySchroll = new JScrollPane(myTextArea, 
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0
import javax.swing.*;
import java.awt.*;

public class Demo extends JFrame {

    private JTextArea textArea;
    private JScrollPane scroll;

    Demo(){
        super("Write here...");
        textArea = new JTextArea();
        scroll = new JScrollPane(textArea);
        scroll.setVerticalScrollBarPolicy(22); /*22 is a const value for always vertical */
        add(scroll, BorderLayout.CENTER);

        setSize(270,270);
        setVisible(true);

    }

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



}

Output of the code : See

Rajan saha Raju
  • 794
  • 7
  • 13