实现 JScrollPane 自动滚动

import java.awt.Point;
import javax.swing.DefaultListModel;
import javax.swing.JScrollBar;
/**
* <p>AutoScroll.java</p>
* <p>Created on Apr 17, 2009, 3:48:21 PM</p>
* <p>Copyright (c) 2007-2009. CUCKOO Workgroup, USTC, P.R.China</p>
* @author Ren Jian
*/
public class AutoScroll {
    private javax.swing.JList jList;
    private javax.swing.JScrollPane jScrollPane;
    private DefaultListModel listModel = new DefaultListModel();
    private void search(String text) {
        int index = listModel.indexOf(text);
        if (index != -1) {
            jList.setSelectedIndex(index);
            Point p = jList.indexToLocation(index);//获得index的位置
            JScrollBar jScrollBar = jScrollPane.getVerticalScrollBar();//获得垂直滚动条
            jScrollBar.setValue(p.y);//设置垂直滚动条位置
        } else {
            System.out.println("not match");
        }
    }
}

你可能感兴趣的:(scroll)