Resizing issue with canvas within jscrollpane within jsplitpane

Instead of setPreferredSize(), let your components calculate their own preferred size and pack() the enclosing Window to accommodate. The example below adds an instance of draw.GraphPanel to the top and a corresponding control panel to the bottom.

image

import draw.GraphPanel;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

/**
 * @see https://stackoverflow.com/q/11942961/230513
 */
public class SplitGraph extends JPanel {

    public SplitGraph() {
        super(new GridLayout());
        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        GraphPanel graphPanel = new GraphPanel();
        split.setTopComponent(new JScrollPane(graphPanel));
        split.setBottomComponent(graphPanel.getControlPanel());
        this.add(split);
    }

    private void display() {
        JFrame f = new JFrame("SplitGraph");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new SplitGraph().display();
            }
        });
    }
}

Leave a Comment