我有一个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
错误。
任何帮助将不胜感激!
答案 0 :(得分:1)
您可以在范围或类属性中使用变量。
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();
}
}