将输入值设置为 JScrollBar 的值

Set input value the value of JScrollBar

我有一个 jScrollbar,当我滚动它时(它的值从 0 到 100),我想在文本字段中显示该值。 这是如何从 jScrollBar 获取值

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

但是我无法将它放入输入中,因为我收到 cannot make static reference to non-static 错误。

任何帮助将不胜感激!

您可以选择在范围内使用变量或 class 属性。

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();
   }
}