Har*_*sha 7 java swing jscrollpane
我有一个JScrollPane,它包含一个高大的JPanel,这个大型JPanel包含更多的Jpanels,就像在图像中一样.其中一些面板包含一个JLabel,我用它来显示标题.在顶部,有JLabel,其编号与标题标签中的标题编号相匹配.我需要做的是当我从顶部标签列表中单击标签时,JScrollBar应滚动到放置该标签的位置.
我不知道这是否可能,但如果有人知道如何滚动到JScrollPane中的特定位置,请帮助我.
假设您希望包含标签的整个面板可见:
Container parent = titleLabel.getParent();
parent.scrollRectToVisible(parent.getBounds());
Run Code Online (Sandbox Code Playgroud)
没有必要访问包含视口/ scrollPane除外(总是有一个除外,不是它:-)
编辑
@MadProgrammer的代码片段:-) - 但是懒得删除SwingX的每一个痕迹,所以我们走了:
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);
Run Code Online (Sandbox Code Playgroud)
这是可行的.
您需要JLabel
在标题中引用它以及它在视图中链接到的位置(JPanel
).获得此链接后,您可能需要确定JLabel
"JPanel"中的位置.
您可以使用该JViewport.scrollRectToVisible(Rectangle)
方法滚动到该位置.
JLabel labelInPane = //... reference lookup
Rectangle bounds = labelInPane.getBounds();
// You may need to convert the point to meet the requirements of the parent container...
// bounds.setLocation(SwingUtilities.convertPoint(labelInPane, bounds.getPoint(), topLevelParentPaneInScrollPane));
scrollPane.getViewport().scrollRectToVisible(bounds);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7977 次 |
最近记录: |