Java :Add scroll into text area

Ravi picture Ravi · Apr 16, 2012 · Viewed 153.9k times · Source

How can i add the scroll bar to my text area. i have tried with this code but it's not working.

            middlePanel=new JPanel();
        middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));

        // create the middle panel components

        display = new JTextArea(16, 58);
        display.setEditable(false); // set textArea non-editable
        scroll = new JScrollPane(display);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        //Add Textarea in to middle panel
        middlePanel.add(scroll);
        middlePanel.add(display);

Thanks

Answer

Mikle Garin picture Mikle Garin · Apr 16, 2012

After adding JTextArea into JScrollPane here:

scroll = new JScrollPane(display);

You don't need to add it again into other container like you do:

middlePanel.add(display);

Just remove that last line of code and it will work fine. Like this:

    middlePanel=new JPanel();
    middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));

    // create the middle panel components

    display = new JTextArea(16, 58);
    display.setEditable(false); // set textArea non-editable
    scroll = new JScrollPane(display);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    //Add Textarea in to middle panel
    middlePanel.add(scroll);

JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:

new JScrollPane( myComponent ) 

or set view like this:

JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );

Additional:

Here is fully working example since you still did not get it working:

public static void main ( String[] args )
{
    JPanel middlePanel = new JPanel ();
    middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

    // create the middle panel components

    JTextArea display = new JTextArea ( 16, 58 );
    display.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane ( display );
    scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

    //Add Textarea in to middle panel
    middlePanel.add ( scroll );

    // My code
    JFrame frame = new JFrame ();
    frame.add ( middlePanel );
    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}

And here is what you get: enter image description here