Java Swing How to - Set JScrollBar Vertical/Horizontal








Question

We would like to know how to set JScrollBar Vertical/Horizontal.

Answer

import java.awt.BorderLayout;
/*from  ww w  . j  a  v a2 s .  co m*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Main extends JPanel {
  int TA_ROWS = 25;
  int TA_COLS = 60;
  JTextField inputField = new JTextField();
  JTextArea talkArea = new JTextArea(TA_ROWS, TA_COLS);

  public Main() {
    JScrollPane talkPane = new JScrollPane(talkArea,
        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JScrollPane inputPane = new JScrollPane(inputField,
        JScrollPane.VERTICAL_SCROLLBAR_NEVER,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    int gap = 10;
    setLayout(new BorderLayout(gap, gap));
    add(talkPane, BorderLayout.CENTER);
    add(inputPane, BorderLayout.SOUTH);
  }
  public static void main(String[] args) {
    JFrame f = new JFrame("Main");
    f.getContentPane().add(new Main());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
  }
}