paula boules paula boules - 2 years ago 131
Java Question

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.setBounds(50, 30, 500, 500);

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

this.setSize(600, 600);
private class MyPanel extends JPanel {
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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download