2011-05-19 49 views

回答

2

看看Center Line in Scroll Pane。它將插入符號垂直居中,但將插入符號水平居中也很重要。

下面是修改代碼,以便它可以水平中心:

public static void centerLineInScrollPane(JTextComponent component) 
{ 
    Container container = SwingUtilities.getAncestorOfClass(JViewport.class, component); 

    if (container == null) return; 

    try 
    { 
     Rectangle r = component.modelToView(component.getCaretPosition()); 
     JViewport viewport = (JViewport)container; 

     int extentWidth = viewport.getExtentSize().width; 
     int viewWidth = viewport.getViewSize().width; 

     int x = Math.max(0, r.x - (extentWidth/2)); 
     x = Math.min(x, viewWidth - extentWidth); 

     int extentHeight = viewport.getExtentSize().height; 
     int viewHeight = viewport.getViewSize().height; 

     int y = Math.max(0, r.y - (extentHeight/2)); 
     y = Math.min(y, viewHeight - extentHeight); 

     viewport.setViewPosition(new Point(x, y)); 
    } 
    catch(BadLocationException ble) {} 
} 
+0

非常感謝您!有沒有辦法讓它滾動更平滑,這在閱讀時看起來相當干擾。 – Magreet 2011-05-20 13:07:39

0

這是我如何調整它:

int y = Math.max(0, r.y - (extentHeight/2)); 
      y = Math.min(y, viewHeight - extentHeight); 
      int oldY = viewport.getViewPosition().y; 
      for(int i = oldY;i<y;i++){ 
      viewport.setViewPosition(new Point(0, i)); 
       Thread.sleep(10); 
      } 
相關問題