Pergunta

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.

Foi útil?

Solução 3

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

Instead of this:
imagePane.add(canvas);

Outras dicas

Make sure you are using all light weight components (JPanel, JScrollPane, etc). I realize you named your own subclass of JPanel Canvas, but it's somewhat confusing in your code and description because Canvas and ScrollPane are AWT classes.

In your comments you said imagePane is a ScrollPane (I'm assuming you meant JScrollPane). If that's is so then imagePane.setLayout is NOT appropriate, and should be removed. Your code should be the following:

Canvas canvas = new Canvas();
canvas.setImage( someImageFile );
canvas.setSizeFromLoaded();

JScrollPane imagePane new JScrollPane( canvas );
imagePane.setBackground(new java.awt.Color(153, 153, 153));
imagePane.setBorder( null );

jSplitPane2.setRightComponent( imagePane );

That will work provided setSetFromLoaded() is able to set the PreferredSize of the canvas based on the size of the image. If it's not ready to calculate it's size because the image hasn't loaded yet (remember this often happens on another thread), then you may need to move the calculations into validate() and do them at a later point. For example, why overriding doLayout() you can calculate your preferred size when the component is revalidated(). You should also consider subclassing JComponent instead of JPanel since you don't have any need to add any children. Same thing applies to JComponent as JPanel.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top