简体   繁体   English

使用GroupLayout布置的面板使scrollRectToVisible起作用

[英]Making scrollRectToVisible work with a panel laid out with GroupLayout

A rather minimal example: This lays out a JLabel in a JPanel , stuffs the JPanel into a JScrollPane , and sticks that in a JFrame . 一个非常简单的示例:这在JPanel布置了一个JLabel ,将JPanel JPanelJScrollPane ,并将其JFrameJFrame I then want the pane to scroll so as to make the JLabel visible, but it does not do so. 然后,我希望窗格滚动以使JLabel可见,但它不这样做。 I've tried calling scrollRectToVisible on the label and the panel, with no luck, messed around with viewports, with no luck, tried setting scrollbar values manually, with no luck. 我试过在标签和面板上调用scrollRectToVisible ,但没有运气,视口混乱,没有运气,尝试手动设置滚动条值,没有运气。 Clearly I'm doing something stupid, but I can't see what. 显然我在做一些愚蠢的事情,但是我看不到。

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

Code works fine for me using JDK7 on Windows7. 在Windows7上使用JDK7的代码对我来说很好用。

If you have an issue on a different version then you can try: 如果您在其他版本上有问题,则可以尝试:

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        fish.scrollRectToVisible(fish.getBounds());
    }
});

This just makes sure the scrollRectToVisible() is added to the end of the EDT so it should be processed after all the initial logic to display the frame has occurred. 这只是确保将scrollRectToVisible()添加到EDT的末尾,因此应在显示帧的所有初始逻辑发生之后进行处理。

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

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