Search code examples
javaswingjpanelmixingjava-canvas

JPanel placed Behind JScrollPanel


I have this code, where Canvas is a class I made that extends JPanel it holds an image. But when I use it, it places the canvas not on top of the JScrollPane, but behind it. Why is it doing that?

Here is how the ScrollPanel is created:

imagePane.setBackground(new java.awt.Color(153, 153, 153));
imagePane.setBorder(null);
jSplitPane2.setRightComponent(imagePane);

Here is the placement of my Panel within the ScrollPanel

Canvas canvas = new Canvas();
canvas.setVisible(true);
canvas.setImage(file);
imagePane.setLayout(new GridBagLayout());
canvas.setSizeFromLoaded();
imagePane.add(canvas);
imagePane.repaint();

The canvas class doesn't do anything with placement of the Panel, all it does is build and modify it. I did have a JPanel there and it worked, but once I switched it out with a JScrollPanel it started placing the canvas behind it.


Solution

  • The problem I came up with to fix this is to use this:
    imagePane.getViewport().add(canvas);

    Instead of this:
    imagePane.add(canvas);