What's the difference: getValueIsAdjusting () in JScrollBar and AdjustmentEvent? + How to listen to JScrollBar buttons?

There are actually two questions:

Question One : What is the difference between getValueIsAdjusting()

the JScrollBar and the AdjustmentEvent

I tried them with some code to check if there is any difference, but I didn't have them !. Here is some 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 above code will print the "AdjustmentEvent" and "JScrollBar" lines sequentially. there seems to be no difference between them!

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


Question Two :

How to listen to JScrollBar buttons? if you tested the above code, it prints lines when you move the pen or click on the bar, but not when you click on the JScrollBar buttons!

+3


source to share


1 answer


Add another event (as mentioned here ) in the class adjustmentValueChanged

class AdjustmentListener

.

If the type is an event AdjustmentEvent.TRACK

, then also print the instruction.



 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 fix the button click action to JScrollBar

.

+4


source







All Articles