Java Swing How to - Add JScrollbar when text goes over the width of the window








Question

We would like to know how to add JScrollbar when text goes over the width of the window.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
/*  www .  j  a va  2s  . c o m*/
public class Main extends JFrame {
  public Main() {
    JScrollPane scrollPane = new JScrollPane();
    JTextPane textPane = new JTextPane();

    scrollPane.setViewportView(textPane);
    add(scrollPane);

    setTitle("Main");
    setSize(300, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }

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