如何滚动到JScrollPane中的特定位置 [英] How to scroll to a specific location in a JScrollPane

查看:160
本文介绍了如何滚动到JScrollPane中的特定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JScrollPane,它包含一个高度很大的JPanel.这个大的JPanel如图所示,其中包含更多的Jpanels.其中一些面板包含一个我用来显示标题的JLabel.在顶部,有JLabel,其编号与标题标签中的标题编号匹配.我需要做的是,当我从顶部标签列表中单击一个标签时,JScrollBar应该滚动到该标签的放置位置.

I have a JScrollPane which contains a JPanel which has large height, This large JPanel contain more Jpanels in it as in the image. Some of those panels contains a JLabel which I used to show titles. At the top, there are JLabels which have numbers matching the title numbers in the title labels. What I need to do is when I click a label from the top label list the JScrollBar should scroll to the position where that label is placed.

我不知道这是否可行,但是如果有人知道如何滚动到JScrollPane中的特定位置,请帮助我.

I don't know whether this is possible or not, but if anyone know how to scroll to a specific position in a JScrollPane please assist me.

推荐答案

假定您希望整个包含标签作为标题的面板可见:

Assuming you want the whole panel that contains the label as title to be visible:

Container parent = titleLabel.getParent();
parent.scrollRectToVisible(parent.getBounds());

除了(总是存在一个例外,不是:-)

There's no need to access the containing viewport/scrollPane except (there's always an except, isn't it :-)

  • 对scrollRectToVisible进行调用的组件具有自定义实现(例如文本组件
  • 如果该方法到达的默认位置不符合您的意愿

修改

@MadProgrammer的代码段:-)-但是太懒了,无法删除SwingX的所有痕迹,所以我们开始:

a code snippet for @MadProgrammer :-) - but too lazy to remove every trace of SwingX, so here we go:

final JLabel last = new JLabel("I'm the last");

int maxRow = 20;
int maxColumn = 10;

JComponent content = new JPanel(new GridLayout(maxRow, maxColumn));
for (int row = 0; row < maxRow; row++) {
    for (int column = 0; column < maxColumn; column++) {
        JComponent parent = new JPanel();
        JLabel label = new JLabel("i'm in " + row + "/" + column);
        if (row == (maxRow - 1) && column == (maxColumn - 1)) {
            label = last;
            last.setBorder(BorderFactory.createLineBorder(Color.RED));
        }
        parent.add(label);
        content.add(parent);
    }
}
JXFrame frame = wrapWithScrollingInFrame(content, "scroll");
Action action = new AbstractAction("scrollLastVisible") {

    @Override
    public void actionPerformed(ActionEvent e) {
        last.scrollRectToVisible(last.getBounds());
    }
};
addAction(frame, action);
show(frame, frame.getPreferredSize().width / 2, frame.getPreferredSize().height / 2);

这篇关于如何滚动到JScrollPane中的特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆