Question

So, I have a JLayeredPane (technically a class subclassing JLayeredPane actually). On that is a JPanel. I want to add a BufferedImage to the Jpanel.

public class BigMap extends JLayeredPane implements MouseListener
  JPanel mapPanel;
  BufferedImage theMap;
  public BigMap (BufferedImage m){
    theMap = m;
    mapPanel = new JPanel();
    add(mapPanel, 0);
    mapPanel.setBounds(0, 0, 640, 640);
    //other unimportant stuff
    }

  @Overrride
  public void paintComponent (Graphics g){
    super.paintComponent(g);
    Graphics2D gmap = (Graphics2D) mapPanel.getGraphics();
    gmap.drawImage(theMap, null, 0, 0);
    //some other stuff which is working just fine
   }

The issue is that the BufferedImage isn't displaying. The JPanel is definately present as I can set its backgroundColour and see it if I wish. I realise that JLayeredPane doesn't have a layout manager and have had to set the bounds for the JPanel but that shouldn't be an issue for the JPanel itself, surely? And given that BufferedImage lacks methods to control its size directly I don't see how I'd overcome that if it were.

Any help appreciated.

Was it helpful?

Solution

The problem here is that you override the paintComponent() method of your layered pane, not the JPanel. The JPanel will paint itself later, as one of the children of your layered pane, and this will wipe out what you painted.

In general, a paintComponent() method should paint into the Graphics that was given to it, not into some other component's graphics.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top