Add AdjustmentListener for JScrollBar in Java

Description

The following code shows how to add AdjustmentListener for JScrollBar.

Example


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
/* w  w w  .  ja v  a2s . c o  m*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;

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

    JPanel main = new JPanel(new GridLayout(2, 1));
    JPanel scrollBarPanel = new JPanel();
    final JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL, 0, 48, 0, 255);
    int height = scrollBar.getPreferredSize().height;
    scrollBar.setPreferredSize(new Dimension(175, height));
    scrollBarPanel.add(scrollBar);
    main.add(scrollBarPanel);

    frame.add(main, BorderLayout.CENTER);

    scrollBar.addAdjustmentListener(new AdjustmentListener() {
      public void adjustmentValueChanged(AdjustmentEvent e) {
        System.out.println("JScrollBar's current value = " + scrollBar.getValue());
      }
    });

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Add AdjustmentListener for JScrollBar in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer