Java JPanel in JScrollPane?

我有一个JFrame,在这个JFrame中,我有一个JPanel,我在上面绘制,这个面板可以是任何大小,所以我把它放在JScrollpane中,让我在面板大于窗口屏幕大小时滚动。

不幸的是,没有像我预期的那样工作:

  1. 使 JFrame 窗口小于 JPanel 大小不会显示滚动条

  2. JScrollPane的大小现在似乎锁定在我添加到它的JPanel的大小,就像以前一样,它的大小调整到它的JFrame窗口的边界(它仍然有点这样做,但现在只是垂直的?!)

  3. JPanel似乎假设JScrollpane的大小,无论我为首选大小设置什么

我敢肯定我正在做一些愚蠢的事情,如果有人能指出我最感激的事情!

JPanel imageCanvas = new JPanel(); // 'Canvas' to draw on
JScrollPane scrollPane = new JScrollPane();
    
// set size of 'canvas'
imageCanvas.setMinimumSize(new Dimension(100,100));

// Scroll pane smaller then the size of the canvas so we should get scroll bars right?
scrollPane.setMinimumSize(new Dimension(50,50)); 
    
// Add a border to 'canvas'
imageCanvas.setBorder(BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
    
scrollPane.setViewportView(imageCanvas);

答案 1

setP referSize() 是诀窍,setMinimumSize() 甚至 setSize() 上的组件都会被 JScrollPane 忽略。下面是一个使用红色边框的工作示例。

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

答案 2
// suggest a size of 'canvas'
_ImageCanvas.setPreferredSize(new Dimension(100,100));

// Scroll pane smaller then the size of the canvas so we should get scroll bars right?
_ScrollPane.setPreferredSize(new Dimension(50,50)); 

// ..later 
_Frame.pack();

推荐