Search code examples
javajpaneljscrollpane

JScrollPane is not working with JPanel drawing Graphics


I`m working on project which draws a GUI for graph, it seems that the JScrollPane is not implemented well, as it doesn't work when some nodes are drawn out of bounds of the panel, here is the code :

public class Test extends JFrame {
public Test() {
    // TODO Auto-generated constructor stub
    MyPanel panel = new MyPanel();

    JScrollPane scrollPane = new JScrollPane(panel);
    scrollPane
            .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane
            .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setBounds(50, 30, 500, 500);

    JPanel contentPane = new JPanel(null);
    contentPane.setPreferredSize(new Dimension(600, 600));
    contentPane.add(scrollPane);

    this.setContentPane(contentPane);
    this.pack();
    this.setSize(600, 600);
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}
private class MyPanel extends JPanel {
    @Override
    public void paint(Graphics g) {
        // in panel range
        g.fillOval(0, 200, 100, 100);
        // out of panel range needs scroll bar
        g.fillOval(1000, 200, 100, 100);
    }
}

Solution

  • Your JPanel needs to advertise its size, by implementing getPreferredSize(), just like any other component in Swing does. A JPanel is a component that draws an opaque background (and its children). You are implementing a custom component (that probably doesn't have child components) so you need to give some sizing information to its parent component (here, the scroll pane) to make sure everything is laid out well.

    You shouldn't be setting the bounds on the scroll pane either. Use a LayoutManager to automatically lay out everything. Never hardcode a GUI.