一个相当简单的示例:这在 JPanel
中布置了 JLabel
,将 JPanel
填充到 JScrollPane
中>,并将其粘贴在 JFrame
中。然后我希望滚动 Pane 以使JLabel
可见,但它没有这样做。我尝试在标签和面板上调用 scrollRectToVisible
,但没有运气,用视口(viewport)搞乱,没有运气,尝试手动设置滚动条值,但没有运气。显然我在做一些愚蠢的事情,但我看不出是什么。
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.*;
public class SillyTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JPanel panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
GroupLayout.SequentialGroup seq = layout
.createSequentialGroup();
GroupLayout.ParallelGroup par = layout.createParallelGroup();
JLabel fish = new JLabel("fish");
seq.addGap(3000);
seq.addComponent(fish);
par.addComponent(fish);
par.addGap(200);
layout.setHorizontalGroup(par);
layout.setVerticalGroup(seq);
JScrollPane scrollPane = new JScrollPane(panel);
JFrame frame = new JFrame("whatever this is about");
frame.add(scrollPane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
fish.scrollRectToVisible(fish.getBounds());
}
});
}
}
最佳答案
代码对我来说在 Windows7 上使用 JDK7 运行良好。
如果您在其他版本上遇到问题,可以尝试:
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
fish.scrollRectToVisible(fish.getBounds());
}
});
这只是确保将scrollRectToVisible()添加到EDT的末尾,因此应该在显示帧的所有初始逻辑发生后对其进行处理。
关于java - 使scrollRectToVisible与使用GroupLayout布局的面板一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143972/