Set input value the value of JScrollBar

298 views Asked by At

I have a jScrollbar and when I scroll it (it has values from 0 to 100) I want to display the value in a textfield. This is how to get the value from the jScrollBar

AdjustmentListener adjListener;
adjListener = new AdjustmentListener() {
    public void adjustmentValueChanged(AdjustmentEvent evt) {
        System.out.println(evt.getValue());
    }
};

But i cannot put it in the input as i get cannot make static reference to non-static error.

Any help will be appreciated!

1

There are 1 answers

0
Aubin On BEST ANSWER

You have the choice between using variables in scope or class attributes.

public class Main extends JFrame {

// Attibute version
// private final JTextField textfield = new JTextField( "0000" );

   Main() {
      super( "Hello, scrollbars!" );
      setDefaultCloseOperation( EXIT_ON_CLOSE );
      setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ));

      // this variable may be defined as attribute
      final JTextField textfield = new JTextField( "0000" );
      add( textfield );

      final JScrollPane scrollPane =
         new JScrollPane(
            new JList<>(
               new String[]{
                  "Hello", "Scrollbars",
                  "Hello", "Scrollbars",
                  "Hello", "Scrollbars",
                  "Hello", "Scrollbars",
                  "Hello", "Scrollbars",
               }));
      scrollPane.getVerticalScrollBar().addAdjustmentListener(
         e -> textfield.setText( String.format( "%04d", e.getValue())));
      add( scrollPane );

      pack();
      setLocationRelativeTo( null );
      setVisible( true );
   }

   public static void main( String[] args ) {
      new Main();
   }
}