[英]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.
我在JScrollPane中有一个JPanel。 JPanel contains six panels that are loaded dynamically.
JPanel包含六个动态加载的面板。 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
我的scrollPane已以这种方式创建
JScrollPane scrollPane= new JScrollPane();
scrollPane.setBounds(panel.getBounds());
scrollPane.setViewportView(panel);
Can you help me? 你能帮助我吗?
panel.scrollRectToVisible(scrollPane.getBounds());
should be panel.scrollRectToVisible(JPanelAddedOnRuntime.getBounds());
应该是
panel.scrollRectToVisible(JPanelAddedOnRuntime.getBounds());
rest of code (posted here) coudn't be works, 其余代码(发布在此处)可能无法正常工作,
for better help sooner post an SSCCE , short, runnable, compilable 为了更好地帮助,尽快发布SSCCE ,简短,可运行,可编译
EDIT 编辑
works, again you would need to re_read my above 3rd. 工作,再次,您将需要重新阅读我上面的3。 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();
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.