繁体   English   中英

滚动到JScrollPane内部的顶部JPanel

[英]Scrolling to the top JPanel inside a JScrollPane

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

panel.scrollRectToVisible(scrollPane.getBounds());

但这是行不通的。 我的scrollPane已以这种方式创建

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

你能帮助我吗?

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

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

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

编辑

工作,再次,您将需要重新阅读我上面的3。

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();
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM