我有一个JSrcollPane,里面装一个JTree,因为JTree节点较多,所以要有下拉框;现在我用程序控制选中了JTree的一个节点,可是因为这个节点在很下面,显示不出来,只要通过下拉才能看见;所以我希望用程序控制下拉框自动下拉,请问怎么才能实现,网上有说用scrollpane.getViewport().setViewPosition(point)可以实现,可是这个Point取不到啊,高手指教

解决方案 »

  1.   

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

  2.   

    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;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.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();
     }}xue xile
      

  3.   

    问题是treeNode不是component啊,没有getLocation()这个方法
      

  4.   

    用 Rectangle getPathBounds(TreePath path) 或 Rectangle getRowBounds(int row)方法得到node的位置,再用 JTree的 void scrollRectToVisible(Rectangle aRect) 方法。