【发布时间】:2016-06-10 00:42:56
【问题描述】:
执行此代码会产生非常奇怪的行为。 运行时,尝试调整大小并输入以了解我的意思。
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() 也是如此。 为什么会有不同的行为?
【问题讨论】:
标签: java swing jscrollpane