如何调整滚动条在滚动窗格中的位置 [英] How to adjust position of scroll in the scrollpane
本文介绍了如何调整滚动条在滚动窗格中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了JTextpane,并在textpane中插入了组件(像Jtextarea这样的组件).当我在该JTextpane中插入新组件时,JTextpane的Jscrollpane(的垂直滚动条)会自动设置为底部.我想将其设置为最高位置.我该怎么办
I have created JTextpane and inserted components inside textpane (components like Jtextarea). (vertical scrollbar of )Jscrollpane of JTextpane is automatically set to bottom when I insert new components in that JTextpane. I want to keep it to be set to the top position. How can I do this
谢谢苏尼尔·库马尔·萨胡(Sunil Kumar Sahoo)
Thanks Sunil Kumar Sahoo
推荐答案
这是我使用的实用程序类.可以用于滚动到 JScrollPane
的顶部,底部,左侧,右侧或水平/垂直中心.
Here's a utility class I use. It can be used to scroll to the top, bottom, left, right or horizonatal / vertical center of a 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);
}
}
这篇关于如何调整滚动条在滚动窗格中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文