How to use scrollbar and react to its action : ScrollBar « Swing JFC « Java

How to use scrollbar and react to its action

How to use scrollbar and react to its action
import java.awt.Adjustable;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;

public class ScrollBarColorSelect extends JFrame implements AdjustmentListener {

  private JLabel redLabel;

  private JLabel greenLabel;

  private JLabel blueLabel;

  private JScrollBar red;

  private JScrollBar green;

  private JScrollBar blue;

  private JPanel colorPanel;

  public ScrollBarColorSelect() {
    setSize(300, 200);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {

    Container contentPane = getContentPane();

    JPanel p = new JPanel();
    p.setLayout(new GridLayout(3, 2,3,3));

    p.add(redLabel = new JLabel("Red 0"));
    p.add(red = new JScrollBar(Adjustable.HORIZONTAL, 0, 0, 0, 255));

    p.add(greenLabel = new JLabel("Green 0"));
    p.add(green = new JScrollBar(Adjustable.HORIZONTAL, 0, 0, 0, 255));

    p.add(blueLabel = new JLabel("Blue 0"));
    p.add(blue = new JScrollBar(Adjustable.HORIZONTAL, 0, 0, 0, 255));

    contentPane.add(p, "South");

    colorPanel = new JPanel();
    colorPanel.setBackground(new Color(0, 0, 0));
    contentPane.add(colorPanel, "Center");

  public void adjustmentValueChanged(AdjustmentEvent evt) {
    redLabel.setText("Red " + red.getValue());
    greenLabel.setText("Green " + green.getValue());
    blueLabel.setText("Blue " + blue.getValue());
    colorPanel.setBackground(new Color(red.getValue(), green.getValue(),


  public static void main(String[] args) {
    JFrame f = new ScrollBarColorSelect();;

Related examples in the same category

1.Accessible Scroll Demo Accessible Scroll Demo
2.A quick demonstration of JScrollBar both vertical and horizontalA quick demonstration of JScrollBar both vertical and horizontal
3.JScrollPane: Button Corner SampleJScrollPane: Button Corner Sample
4.JScrollPane CornerJScrollPane Corner
5.Expandable SplitPaneExpandable SplitPane
6.ScrollBar PiecesScrollBar Pieces
7.Listening for Scrollbar Value Changes in a JScrollPane Container
8.Get the default scrollbar policy
9.Make the scrollbars always appear
10.Make the scrollbars never appear
11.JScrollBar and Adjustment event
12.JScrollPane to hold scrollable component
13.Use Adjustment Events in Swing
14.Always display scrollbar