Java JPanel inside JScrollPane?

后端 未结 5 1191
自闭症患者
自闭症患者 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: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);
                }
            });
        }
    }
    

提交回复
热议问题