如何设置JPanel固定大小,以便显示JScrollPane(滚动)



我正在编写一些代码。JFrame包含特定尺寸的JPanel。下面是我的代码:

import javax.swing.*; 
import java.awt.*; 
public class ScrollPane extends JFrame { 
    public ScrollPane() {
        super("Title");
        setLayout(new BorderLayout());
        setSize(320,240);
        JScrollPane scroller = new JScrollPane(new DrawingPane()); 
        scroller.setPreferredSize(new Dimension(320,240)); 
        add(scroller); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    } 
    private class DrawingPane extends JPanel {
        public DrawingPane(){
            super();
            setSize(640,480);
            setMinimumSize(new Dimension(320,240));
        }
    }
    public static void main(String[] args) {
        new ScrollPane();
    } 
}

即使为JPanel设置了最小大小,卷轴也不会出现。

所有组件都负责确定它们的首选大小,以便布局管理器可以正常工作。当进行自定义绘画时,您需要重写自定义组件的getPreferredSize()以返回组件的Dimension。

阅读Swing教程中关于自定义绘画的部分,了解更多信息和工作示例。

您还需要为绘图面板设置首选大小:

private class DrawingPane extends JPanel {
        public DrawingPane(){
            super();
            setPreferredSize(new Dimension(640,480));
            setMinimumSize(new Dimension(320,240));
        }
    }

最新更新