What is the difference: getValueIsAdjusting() in both JScrollBar and AdjustmentEvent? + How to listen to the buttons of JScrollBar?

StackOverflow https://stackoverflow.com/questions/14539583

Question

They are actually two questions:

The First question: What is the difference between getValueIsAdjusting() in both JScrollBar and of AdjustmentEvent

I tried them with some code to test if any difference, but I didn't get any!. Here is the code to show How I tested them.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollTest extends JPanel
{
    JPanel panel;
    JScrollBar scroll;

    public ScrollTest()
    {
        scroll = new JScrollBar(JScrollBar.HORIZONTAL, 0, 6, 0, 300);
        scroll.addAdjustmentListener(ScrollListener);
        panel = new JPanel(new GridLayout(1, 0));
        panel.add(scroll);
        this.setLayout(new BorderLayout());
        this.add(panel);
    }

    AdjustmentListener ScrollListener = new AdjustmentListener()
    {
        @Override
        public void adjustmentValueChanged(AdjustmentEvent e)
        {
           if(e.getValueIsAdjusting())
           {
               System.out.println("AdjustmentEvent");
           }

           if(scroll.getValueIsAdjusting())
           {
              System.out.println("JScrollBar");
           }

        }
    };

    private static void createAndShowGUI()
    {
        JFrame frame;
        frame = new JFrame("Scroll Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(880, 100);
        frame.add(new ScrollTest(), BorderLayout.CENTER);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}

The code above will print "AdjustmentEvent" and "JScrollBar" strings in sequence. it seems there is no difference between them!

The important point is when/for what to use each?


The Second question:

How to listen to JScrollBar buttons? if you tested the above code, it prints the strings when you move the knob or click on the strip, but not when you click the buttons of the JScrollBar!

Was it helpful?

Solution

Add one more event (as stated here) in the adjustmentValueChanged of AdjustmentListener class.

If event type is AdjustmentEvent.TRACK then also print a statement.

 if(e.getValueIsAdjusting())
 {
   System.out.println("AdjustmentEvent");
 }

 if(scroll.getValueIsAdjusting())
 {
   System.out.println("JScrollBar");
 }

 if(e.getAdjustmentType() == AdjustmentEvent.TRACK) 
 { 
   System.out.println("The button in scrollbar clicked");
 }

This will capture the button click action on the JScrollBar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top