欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

控制JScrollPane自动滚动到某组件位置,jscrollpane组件,当JScrollPane

来源: javaer 分享于  点击 47189 次 点评:236

控制JScrollPane自动滚动到某组件位置,jscrollpane组件,当JScrollPane


当JScrollPane中有很多组件的时候,如何控制JScrollPane自动滚动到某个组件的位置。

import java.awt.GridLayout;import java.awt.Point;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JScrollBar;import javax.swing.JScrollPane;/** * 控制JScrollPane自动滚动到某组件位置 * @author 五斗米 <如转载请保留作者和出处> * @blog <a href="http://blog.csdn.net/mq612">http://blog.csdn.net/mq612 */public class Test extends JFrame { private JScrollPane sp = null; private JPanel pane = null; private JButton [] button = null; public Test() {  pane = new JPanel(new GridLayout(20, 1));  button = new JButton[20];  for(int i = 0; i < button.length; i++){ // 将所有按钮添加到panel容器中   button[i] = new JButton("[ " + i + " ]");   pane.add(button[i]);  }  sp = new JScrollPane(pane); // 将panel放到JScrollPane中  this.getContentPane().add(sp);  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  this.setSize(350, 200);  this.setLocationRelativeTo(null);  this.setVisible(true);  // 现在确定button[12]的位置,如果是JTree则需要确定某个节点的位置  Point p = button[12].getLocation();  // 获取JScrollPane中的纵向JScrollBar  JScrollBar sBar = sp.getVerticalScrollBar();  // 设置滚动到button[12]所在位置  sBar.setValue(p.y); } public static void main(String[] arg) {  new Test(); }}//该片段来自于http://byrx.net
相关栏目:

用户点评