将组件添加到 JScrollPane 有奇怪的行为

Adding Component to JScrollPane has weird behavior

执行这段代码会产生非常奇怪的行为。 当 运行 时,请尝试调整大小并键入以了解我的意思。

import java.awt.BorderLayout;
import javax.swing.*;

public class FrameWithScrollPanel extends JFrame {
public static void main(String[] args) {
    FrameWithScrollPanel myFrame = new FrameWithScrollPanel();
}


public FrameWithScrollPanel()
{
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    JTextArea textArea1 = new JTextArea(5, 30);
    JTextArea textArea2 = new JTextArea(5, 30);

    JPanel jPanel = new JPanel();
    jPanel.setSize(400,400);
    jPanel.setLayout(new BorderLayout());
    jPanel.add(textArea1, BorderLayout.NORTH);
    jPanel.add(textArea2, BorderLayout.SOUTH);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.add(jPanel);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    pack();
    setVisible(true);
}
}

现在,替换这两行:

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.add(jPanel);

有了这一行,行为就符合预期。

    JScrollPane scrollPane = new JScrollPane(jPanel);

根据文档,JScrollPane 构造函数接受一个组件,add() 也是如此。 为什么行为不同?

这是错误的:

scrollPane.add(jPanel);

由于您要用此添加替换 JScrollPane 的所有重要视口,因此无法正常运行。您应该按照 JScrollPane tutorial and JScrollPane API:

将其添加到 JScrollPane 的视口中
scrollPane.setViewportView(jPanel);

scrollPane.getViewport().add(jPanel);

故事的寓意:如有疑问,请阅读文档。

请注意,如果将 jPanel 传递给 JScrollPane 的构造函数,

JScrollPane scrollPane = new JScrollPane(jPanel);

它会自动为您将组件放入视口中。

根据 API:

public JScrollPane(Component view)
Creates a JScrollPane that displays the contents of the specified component, where both horizontal and vertical scrollbars appear whenever the component's contents are larger than the view.
Parameters:
view - the component to display in the scrollpane's viewport