0

多くの人がこの質問をしたことは知っていますが、まだこの問題を解決できません。JScrollPane 内に JPanel があります。JPanel には、動的にロードされる 6 つのパネルが含まれています。パネルがロードされると、システムはパネルの中央まで垂直自動スクロールを行います。私はこれを避ける必要があるので、これで試しました:

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、短い、実行可能、コンパイル可能をすぐに投稿してください

編集

動作しますが、上記の 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();
            }
        });
    }
}
于 2013-10-16T09:58:19.333 に答える