如何调整滚动窗格中滚动的位置

我创建了JTextpane并在textpane中插入了组件(像Jtextarea这样的组件)。 (垂直滚动条)当我在JTextpane中插入新组件时,JTextpane的Jscrollpane会自动设置为底部。 我想让它保持在最高位置。 我怎样才能做到这一点

谢谢Sunil Kumar Sahoo

这是我使用的实用程序类。 它可用于滚动到JScrollPane的顶部,底部,左侧,右侧或水平/垂直中心。

 public final class ScrollUtil { public static final int NONE = 0, TOP = 1, VCENTER = 2, BOTTOM = 4, LEFT = 8, HCENTER = 16, RIGHT = 32; private static final int OFFSET = 100; // Required for hack (see below). private ScrollUtil() { } /** * Scroll to specified location. eg scroll(component, BOTTOM);. * * @param c JComponent to scroll. * @param part Location to scroll to. Should be a bit-wise OR of one or moe of the values: * NONE, TOP, VCENTER, BOTTOM, LEFT, HCENTER, RIGHT. */ public static void scroll(JComponent c, int part) { scroll(c, part & (LEFT|HCENTER|RIGHT), part & (TOP|VCENTER|BOTTOM)); } /** * Scroll to specified location. eg scroll(component, LEFT, BOTTOM);. * * @param c JComponent to scroll. * @param horizontal Horizontal location. Should take the value: LEFT, HCENTER or RIGHT. * @param vertical Vertical location. Should take the value: TOP, VCENTER or BOTTOM. */ public static void scroll(JComponent c, int horizontal, int vertical) { Rectangle visible = c.getVisibleRect(); Rectangle bounds = c.getBounds(); switch (vertical) { case TOP: visible.y = 0; break; case VCENTER: visible.y = (bounds.height - visible.height) / 2; break; case BOTTOM: visible.y = bounds.height - visible.height + OFFSET; break; } switch (horizontal) { case LEFT: visible.x = 0; break; case HCENTER: visible.x = (bounds.width - visible.width) / 2; break; case RIGHT: visible.x = bounds.width - visible.width + OFFSET; break; } // When scrolling to bottom or right of viewport, add an OFFSET value. // This is because without this certain components (eg JTable) would // not scroll right to the bottom (presumably the bounds calculation // doesn't take the table header into account. It doesn't matter if // OFFSET is a huge value (eg 10000) - the scrollRectToVisible method // still works correctly. c.scrollRectToVisible(visible); } } 

我发现最简单的方法是:

 public void scroll(int vertical) { switch (vertical) { case SwingConstants.TOP: getVerticalScrollBar().setValue(0); break; case SwingConstants.CENTER: getVerticalScrollBar().setValue(getVerticalScrollBar().getMaximum()); getVerticalScrollBar().setValue(getVerticalScrollBar().getValue() / 2); break; case SwingConstants.BOTTOM: getVerticalScrollBar().setValue(getVerticalScrollBar().getMaximum()); break; } } 

我将它放在扩展JScrollPane的对象中,但您也可以在所有getVertivalScrollBar()之前添加JScrollPane的名称。 对于CENTER,有两个setValue() ,因为getMaximum()返回JScrollBar的底部,而不是它返回的最低值。 这也适用于使用getHorizontalScrollBar()代替getverticalScrollBar()水平滚动。

应该可以将DefaultCaret更新策略设置为NEVER_UPDATE 。 有关其他用途,请参阅文章区域滚动

您可以使用各种方法,具体取决于滚动窗格内的内容。 请参阅教程 ,最后一节。

jScrollPane.getVerticalScrollBar()的setValue(1)。