Monday, January 8, 2018

Add a scroll bar on a window (java Swing)

This is the code:
import javax.swing.*;
import java.awt.BorderLayout;

public class Main extends JFrame{ //Extending JFrame

 Main(){ //Constructor of Main class
     JTextArea textarea = new JTextArea("This is the JTextArea");

     JScrollPane scrollpane = new JScrollPane(); //This is the scroll bar
     scrollpane.setViewportView(textarea);

     getContentPane().add(scrollpane, BorderLayout.CENTER);
  }

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

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setBounds(10, 10, 300, 200);
     frame.setTitle("This is the title");
     frame.setVisible(true);
 }
}

If you execute the code above, you will see a window will popup:

If you add line breaks a lot, the scroll bar will appear automatically: