gpt4 book ai didi

java - 如何调整滚动 Pane 中滚动的位置

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:46 25 4
gpt4 key购买 nike

我已经创建了 JTextpane 并在 textpane 中插入了组件(组件如 Jtextarea)。当我在该 JTextpane 中插入新组件时,JTextpane 的 Jscrollpane 的(垂直滚动条)自动设置为底部。我想让它保持在顶部位置。我该怎么做

谢谢苏尼尔·库马尔·萨胡

最佳答案

这是我使用的实用程序类。它可用于滚动到 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. e.g. <tt>scroll(component, BOTTOM);</tt>.
*
* @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. e.g. <tt>scroll(component, LEFT, BOTTOM);</tt>.
*
* @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 (e.g. 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 (e.g. 10000) - the scrollRectToVisible method
// still works correctly.

c.scrollRectToVisible(visible);
}
}

关于java - 如何调整滚动 Pane 中滚动的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2544758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com