简体   繁体   中英

Scrolling to the top JPanel inside a JScrollPane

I know a lot of people asked this question, but i still can't resolve this problem. I have a JPanel inside a JScrollPane. JPanel contains six panels that are loaded dynamically. After the panels are loaded the system makes a vertical autoscroll to the middle of the panel. I have to avoid this, so I tried with this:

panel.scrollRectToVisible(scrollPane.getBounds());

But it doesn't work. My scrollPane has been created in this way

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

Can you help me?

  1. panel.scrollRectToVisible(scrollPane.getBounds()); should be panel.scrollRectToVisible(JPanelAddedOnRuntime.getBounds());

  2. rest of code (posted here) coudn't be works,

  3. for better help sooner post an SSCCE , short, runnable, compilable

EDIT

works, again you would need to re_read my above 3rd. point

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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