rstumbaugh
rstumbaugh

Reputation: 192

How to draw an image over JPanels

I have a Battleship game in which I am trying to draw the ships, hits, and misses on the Grid object. Grid is an instance of JPanel with many Blocks. Blocks are JPanels also but are attributes of the Grid. The ships are being drawn on the Grid but under the Blocks. Is it possible to draw over the Blocks? I tried the Glass Pane and it didn't work too well. Any other solutions?

This is how it looks now, the ship is at C3.

Upvotes: 1

Views: 765

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347332

Blocks are JPanels also but are attributes of the Grid. The ships are being drawn on the Grid but under the Blocks.

There's a sneaky way to achieve it, but you may need to change your base layout to GridBagLayout.

Basically, you want to add each Block to its own cell but GridBagLayout will allow you to add components that can expand columns and/or rows, allowing to add your ships that expand over Blocks.

This, of course, assumes you ships and effects are based on components

Upvotes: 0

Sage
Sage

Reputation: 15428

Is it possible to draw over the Blocks? I tried the Glass Pane and it didn't work too well. Any other solutions?

Yes, a non-recommended but sometime useful approach is to use an extended JPanel and override the paint(Graphics g) function:

Class MyGridPane extends JPanel
{

 @Override
    public void paint(Graphics g) {
         super.paint(g); // <----- don't forget to call this

       // then anything you draw will appear above the child component's 
        Graphics2D g2d = (Graphics2D)g.create(); // cloning to work, it is safer aproach
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
        g2d.fillRect(0, 0, getWidth(), getHeight());
        g2d.dispose();// disposing the graphics object 
    }

}

Alternatively you may look into using JLayeredPane to work with a Panel containing your drawn image above the target panel(Grid)'s layer. Check out How to Use Layered Pane

Upvotes: 2

Related Questions