我有一个包含垂直框的 JScrollPane。我在 Box 的顶部插入新的 JPanel。如果我使用滚动条向下滚动,我希望当前 View 保留在我向下滚动到的位置。例如,如果我在框中有 50 个面板并使用滚动条查看面板 20,我希望 View 保留在框 20 上,即使在顶部添加了其他框。此外,如果我使用滚动条向上滚动到顶部,我希望 View 在添加新面板时显示它们。知道怎么做吗?
顺便说一句,没有必要使用 JScrollPane 或 Box。示例代码只是为了帮助解释我正在尝试做的事情。
示例代码:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestScrollPane extends JFrame { JScrollPane scrollPane; Box box; private static int panelCount = 0; public TestScrollPane() { setPreferredSize(new Dimension(200, 400)); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.getVerticalScrollBar().setUnitIncrement(15); box = Box.createVerticalBox(); scrollPane.getViewport().add(box); this.add(scrollPane); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); Timer t = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent ae) { box.add(new TestPanel(), 0); scrollPane.validate(); } }); t.setRepeats(true); t.start(); } public class TestPanel extends JPanel { int myId = panelCount++; public TestPanel() { this.setLayout(new GridBagLayout()); this.setBorder(BorderFactory.createBevelBorder(1)); JLabel label = new JLabel("" + myId); label.setHorizontalAlignment(JLabel.CENTER); label.setVerticalAlignment(JLabel.CENTER); this.setMaximumSize(new Dimension(100, 100)); this.setPreferredSize(new Dimension(100, 100)); this.add(label); } } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { TestScrollPane testScrollPane = new TestScrollPane(); } }); } }
编辑: 这就是我最终更改代码的方式。我因为没有看到明显的东西而感到有些愚蠢。无论如何,感谢那些提供帮助的人。
public void actionPerformed(ActionEvent ae) { Point view = scrollPane.getViewport().getViewPosition(); TestPanel panel = new TestPanel(); box.add(panel, 0); scrollPane.validate(); if (view.y != 0) { view.y += panel.getHeight(); scrollPane.getViewport().setViewPosition(view); } }
顺便说一句,我已经将这个问题交叉发布到 http://www.coderanch.com/t/528829/GUI/java/JScrollPane-adding-JPanels-at-top#2398276仅供可能关心的人引用。
最佳答案
您可以获得要使其可见的组件的边界(使用 JComponent 的 getBounds 方法),并将其用作 JViewPort 的 scrollRectToVisible 方法的输入。
关于java - JScrollPane 在顶部添加 JPanels 并保持当前 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5132802/