swing layout - center panel to scroll with multiple JEditorPanes

前端 未结 1 1093
暗喜
暗喜 2021-01-23 13:17

Im having trouble getting Swing layouts to do what I want. I want the Center panel which contains two JEditorPanes to scroll when it contains \'n\' Panes of equal (fixed) height

1条回答
  •  再見小時候
    2021-01-23 13:33

    Here's an sscce that may guide your further efforts. Each panel's preferred size is specified to force the scroll bar to appear; similarly, the frame's overall size is set (after pack()) to force the outer scroll bar to appear. See this Q&A for more. Note also the use of an RFC 2606 compliant URL.

    As an aside, you should probably study layouts before relying too much on a GUI editor.

    image

    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import java.io.IOException;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    
    /**
     * @see https://stackoverflow.com/a/12827643/230513
     * @see https://stackoverflow.com/questions/4755524
     */
    public class HtmlView extends JPanel {
    
        private static final String EXAMPLE = "http://www.example.com";
        private final JEditorPane jep;
    
        public HtmlView(String url) {
            super(new GridLayout(1, 1));
            jep = new JEditorPane();
            try {
                jep.setPage(EXAMPLE);
            } catch (IOException ioe) {
                ioe.printStackTrace(System.err);
            }
            jep.setEditable(false);
            this.add(new JScrollPane(jep));
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(600, 200);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    JFrame f = new JFrame();
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    JPanel panel = new JPanel(new GridLayout(0, 1));
                    panel.add(new HtmlView(EXAMPLE));
                    panel.add(new HtmlView(EXAMPLE));
                    panel.add(new HtmlView(EXAMPLE));
                    f.add(new JScrollPane(panel));
                    f.pack();
                    f.setSize(640, 480);
                    f.setVisible(true);
                }
            });
        }
    }
    

    0 讨论(0)
提交回复
热议问题