ScrollBar 组件在滑动滚动块时就会触发调整事件,为了监听调整事件,必须给 ScrollBar 组件对象添加一个调 整事件监听器
AdjustmentListener。该监听器只有一个方法,其一般格式如下
public void adjustmentValueChanged(AdjustmentEvent e) { //调整滚动条发生 }
假设现有滚动条组件对象 scrollbar,调整事件使用如下。
scrollbar.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { //调整滚动条 do someting } });
实例如下:
package sup.orange.learn; import java.awt.*; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * Created by re-x on 10/27/14. */ public class AdjustmentEventDemo extends Frame { Scrollbar slider; TextField value; Label label; public AdjustmentEventDemo() { super(); init(); } public void init() { setLayout(new GridLayout(1, 3)); slider = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 100); slider.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { value.setText(Integer.toString(((Scrollbar)e.getSource()).getValue())); } }); value = new TextField("0", 5); value.setEditable(false); label = new Label("0~100"); label.setBackground(Color.cyan); add(label); add(slider); add(value); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); setVisible(false); dispose(); System.exit(0); } }); setSize(300, 50); setVisible(true); } public static void main(String[] args) { new AdjustmentEventDemo(); } }
时间: 2024-10-03 22:55:55