Java JPanel inside JScrollPane?

后端 未结 5 1190
自闭症患者
自闭症患者 2020-12-06 10:06

I have a JFrame, in this JFrame I have a JPanel that I draw on, this Panel can be any size and so I placed it into a JScrollpane to let me scroll when the panel is larger th

相关标签:
5条回答
  • 2020-12-06 10:38

    As far as I remember there are 2 options:

    • define the preferredSize of _ImageCanvas
    • create a subclass of JPanel and implement Scrollable: http://docs.oracle.com/javase/7/docs/api/javax/swing/Scrollable.html

    For more details, see the Javadoc: http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html

    0 讨论(0)
  • 2020-12-06 10:42
    // 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();
    
    0 讨论(0)
  • 2020-12-06 10:44

    Check out the Scrollable interface, this may help with the sizing issues.

    These two method maybe helpful:

    boolean getScrollableTracksViewportWidth();
    
    boolean getScrollableTracksViewportHeight();
    
    0 讨论(0)
  • 2020-12-06 10:48
    • Set preferred size on the canvas.
    • Increase dimensions 100,100 is too small atleast on my computer.
    • You may want to use new GridLayout(1,1); for you JFrame if you want the scrollpane to expand when you expand the frame.
    0 讨论(0)
  • 2020-12-06 10:56

    setPreferredSize() is the trick, setMinimumSize() and even setSize() on the component will be ignored by JScrollPane. Here's a working example using a red border.

    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);
                }
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题