Java: Example - JTextArea

This is how the window looks initially. There are no scrollbars visible. They will be added only if there is sufficient data in the JTextArea to make them necessary.
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
// File   : GUI/components/textarea/TextAreaDemoB.java
// Purpose: Illustrate JTextArea contained in JScrollPane
//          where scroll bars appear as needed.
// Author : Fred Swartz, 2006-07-27

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

public class TextAreaDemoB extends JFrame {
    //============================================== instance variables
   JTextArea _resultArea = new JTextArea(6, 20);
        
    //====================================================== constructor
    public TextAreaDemoB() {
        //... Set textarea's initial text, scrolling, and border.
        _resultArea.setText("Enter more text to see scrollbars");
        JScrollPane scrollingArea = new JScrollPane(_resultArea);
        
        //... Get the content pane, set layout, add to center
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(scrollingArea, BorderLayout.CENTER);
        
        //... Set window characteristics.
        this.setContentPane(content);
        this.setTitle("TextAreaDemo B");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.pack();
    }
    
    //============================================================= main
    public static void main(String[] args) {
        JFrame win = new TextAreaDemoB();
        win.setVisible(true);
    }
}
This is how the window looks after typing in a long line of text. A horizontal scrollbar is necessary. It's a bit of a puzzle to me why the vertical scrollbar also appears because it's not needed. If you stretch the window to make it a little higher, the vertical scrollbar then disappears.