0

So I am working on a Java game using a combination of swing components, and Graphics2D.

I have an AbstractLevelView class which contains all of the elements of the game inside. This LevelView component uses a BorderLayout to display a context bar on the left, and a JPanel containing the game grid in the center.

My context bar and gridPanel all work fine, but what I want to do is paint "messages" directly to the AbstractLevelView, but I can't get any painting to work. This is presumably because there is nowhere to paint due to the nested components.

I've included an abbreviated version of my AbstractLevelView, as well as a test paintComponent method. I have tried using paintComponents, but it doesn't even get called.

Does anyone know what I can do so I can paint on top of my nested components?

public abstract class AbstractLevelView extends AbstractGameView {

    private JPanel gridPanel;
    private ContextBar contextBar;

    public AbstractLevelView(){

        gridPanel = new JPanel();
        add(gridPanel, BorderLayout.CENTER);

        contextBar = new ContextBar();
        add(contextBar, BorderLayout.WEST);
    }

    @Override
public void paintComponent(Graphics g){
    System.out.println("foo");
    Image img = ImageManager.getImage("img.jpg");
    g.drawImage(img, 0, 0, 300, 300, this);
}
}
zalpha314
  • 1,444
  • 4
  • 19
  • 34
  • 2
    Since your question involves drawing on a GUI, I suggest 1) posting an [sscce](http://sscce.org), not a code snippet we can't compile nor run, and 2) posting a picture of what you're getting and a picture of what you want. – Hovercraft Full Of Eels Oct 20 '13 at 22:18
  • 2
    Either use something like a `JLayeredPane` to layer components ontop of each other or the frames glass pane... – MadProgrammer Oct 20 '13 at 22:22
  • 1
    Also consider using a JLayer as a way of "decorating" your JPanel. I've used this with graphics before to good effect. – Hovercraft Full Of Eels Oct 20 '13 at 22:29
  • 1
    If AbstractGameView is a descendant of JPanel, your paintComponent needs to call `super.paintComponent(g)` before doing any drawing. See [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html#callbacks), in particular the section on Swing paint methods. – VGR Oct 20 '13 at 22:43

1 Answers1

0

Thank you MadProgrammer, for suggesting JLayeredPanes. I had attempted to use those back in the earlier stages of my game, but now that I know more about them, I've successfully implemented a solution.

enter image description here

zalpha314
  • 1,444
  • 4
  • 19
  • 34