62,614
社区成员
发帖
与我相关
我的任务
分享
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.plaf.basic.BasicScrollBarUI;
public class MyScrollBar extends JScrollBar{
public MyScrollBar() {
super();
setUI(new MyScrollBarUI());
}
public MyScrollBar(int orientation) {
super(orientation, 0, 10, 0, 100);
setUI(new MyScrollBarUI());
}
class MyScrollBarUI extends BasicScrollBarUI {
protected void installComponents(){
super.installComponents();
incrButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("incrButton");
}
});
decrButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("decrButton");
}
});
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);//居中
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = frame.getContentPane();
JPanel pnl = new JPanel();
pnl.setPreferredSize(new Dimension(200,500));
JScrollPane scrPane = new JScrollPane(pnl);
scrPane.setVerticalScrollBar(new MyScrollBar());
content.add(scrPane);
frame.setVisible(true);
}
}
private ChangeListener fwdAdjustmentEvents = new ModelListener();//实例化了一个ModelListener的对象fwdAdjustmentEvents
public JScrollBar(int orientation, int value, int extent, int min, int max) {//构造函数
...
this.model.addChangeListener(fwdAdjustmentEvents);给JScrollBar添加ChangeListener——fwdAdjustmentEvents
...
}
private class ModelListener implements ChangeListener, Serializable {
public void stateChanged(ChangeEvent e) {
Object obj = e.getSource();
if (obj instanceof BoundedRangeModel) {
int id = AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED;//id赋值AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED
int type = AdjustmentEvent.TRACK;//type赋值AdjustmentEvent.TRACK
BoundedRangeModel model = (BoundedRangeModel)obj;
int value = model.getValue();
boolean isAdjusting = model.getValueIsAdjusting();
fireAdjustmentValueChanged(id, type, value, isAdjusting);//以id、type为参数调用fireAdjustmentValueChanged方法
}
}
}
private void fireAdjustmentValueChanged(int id, int type, int value,
boolean isAdjusting) {
Object[] listeners = listenerList.getListenerList();//把listenerList中的对象全取出来放在listeners数组中
AdjustmentEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i]==AdjustmentListener.class) {
if (e == null) {
e = new AdjustmentEvent(this, id, type, value, isAdjusting);
}
((AdjustmentListener)listeners[i+1]).adjustmentValueChanged(e);//对listeners数组中的对象依次产生adjustmentValueChanged事件
}
}
}