现在的位置: 首页 > 综合 > 正文

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

2013年03月04日 ⁄ 综合 ⁄ 共 1091字 ⁄ 字号 评论关闭

  当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 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();
 }

}

 

抱歉!评论已关闭.