Reputation: 33
When I run the program, the JPanel is not visible. It works without the JScrollPane though. This is driving me crazy! Before, I had it using a Canvas and a ScrollPane. Note that FlowchartPanel extends JPanel.
public class Window extends JFrame{
private FlowchartPanel panel; // contains all the main graphics
private JScrollPane scrollpane; // contains panel
private int canvasWidth, canvasHeight; // the width and height of the canvas object in pixels
private Flowchart flowchart; // the flowchart object
public Window(Flowchart flowchart) {
super();
canvasWidth = 900;
canvasHeight = 700;
this.flowchart = flowchart;
flowchart.setWidth(canvasWidth);
flowchart.setHeight(canvasHeight);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new FlowchartPanel(flowchart);
panel.setPreferredSize(new Dimension(canvasWidth, canvasHeight));
scrollpane = new JScrollPane();
scrollpane.setPreferredSize(new Dimension(canvasWidth, canvasHeight));
scrollpane.add(panel);
add(scrollpane);
//add(panel);
pack();
}
}
Upvotes: 0
Views: 159
Reputation: 324078
Don't add components directly to a JScrollPane
.
The component needs to be added to the JViewPort
of the JScrollPane
The easiest way to do this is to use:
JScrollPane scrollPane = new JScrollPane( panel );
Another way is to replace (add) the component in the viewport is to use:
scrollPane.setViewportView( panel );
panel.setPreferredSize(new Dimension(canvasWidth, canvasHeight));
Don't set the preferred size of a component. Every Swing component is responsible for determining its own preferred size. Instead override the getPreferredSize()
method of your custom panel to return the size. This way as the custom painting changes, you can dynamically change the preferred size as required.
Upvotes: 2