Java Swing How to - Set ScrollBar Policy for JScrollPane








Question

We would like to know how to set ScrollBar Policy for JScrollPane.

Answer

import java.awt.BorderLayout;
//from  w  w w .  j  a  v  a  2s . c om
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends JFrame {

  private JPanel panel = new JPanel();
  private JLabel label = new JLabel("Your Label");
  private JTextArea input = new JTextArea(
      "Enter message");
  public static void main(String[] args) {
    new Main();
  }
  private void loadLabel() {
    label.setBounds(0, 0, 269, 20);
    panel.add(label);

    input.setBounds(0, 20, 300, 60);
    JScrollPane scroll = new JScrollPane(input);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setVisible(true);
    scroll.setBounds(50, 20, 300, 60);
    panel.add(scroll);
  }
  public Main() {
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    setSize(300, 400);
    getContentPane().add(panel, BorderLayout.EAST);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    loadLabel();
  }
}