我有一个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
错误。
任何帮助将不胜感激!
您可以选择在作用域或类属性中使用变量。
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();
}
}