0

我知道很多人问过这个问题,但我仍然无法解决这个问题。我在 JScrollPane 中有一个 JPanel。JPanel 包含六个动态加载的面板。加载面板后,系统会垂直自动滚动到面板中间。我必须避免这种情况,所以我尝试了这个:

panel.scrollRectToVisible(scrollPane.getBounds());

但它不起作用。我的scrollPane就是这样创建的

JScrollPane scrollPane= new JScrollPane();
scrollPane.setBounds(panel.getBounds());
scrollPane.setViewportView(panel);

你能帮助我吗?

4

1 回答 1

5
  1. panel.scrollRectToVisible(scrollPane.getBounds());应该panel.scrollRectToVisible(JPanelAddedOnRuntime.getBounds());

  2. 其余代码(在此处发布)无法正常工作,

  3. 为了获得更好的帮助,请尽快发布SSCCE,简短,可运行,可编译

编辑

工作,你需要重新阅读我上面的第三个。观点

import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ScrollTesting {

    private JPanel panel = new JPanel();
    private JScrollPane scrollPane = new JScrollPane(panel);
    private Vector<JTextField> fieldsVector = new Vector<JTextField>();
    private Dimension preferredSize = new Dimension(400, 40);
    private Font font = new Font("Tahoma", 1, 28);

    public ScrollTesting() {
        panel.setLayout(new GridLayout(100, 1));
        for (int i = 0; i < 100; i++) {
            fieldsVector.addElement(new JTextField());
            fieldsVector.lastElement().setPreferredSize(preferredSize);
            fieldsVector.lastElement().setFont(font);
            panel.add(fieldsVector.lastElement());
        }
        JFrame frame = new JFrame();
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(scrollPane);
        frame.setVisible(true);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JTextField tf = (JTextField) fieldsVector.lastElement();
                panel.scrollRectToVisible(tf.getBounds());
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ScrollTesting scrollTesting = new ScrollTesting();
            }
        });
    }
}
于 2013-10-16T09:58:19.333 回答