setPreferredSize()是技巧,JScrollPane将忽略组件上的setMinimumSize()甚至setSize()。这是一个使用红色边框的工作示例。
import java.awt.*;import javax.swing.*;public class Scroller extends Jframe { public Scroller() throws HeadlessException { final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createLineBorder(Color.red)); panel.setPreferredSize(new Dimension(800, 600)); final JScrollPane scroll = new JScrollPane(panel); setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); setLayout(new BorderLayout()); add(scroll, BorderLayout.CENTER); setSize(300, 300); setVisible(true); } public static void main(final String[] args) throws Exception { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Scroller().setVisible(true); } }); }}


