Kamora
Kamora

Reputation: 83

How to draw on a JPanel using Graphics

I am working on a project and i have already made a menu and a JPanel but now i want to draw over the JPanel and add some HUD to my game.

I am providing a picture with the final panel of my game and i want to add at the left a blue rectangle with the player heads and at the right another rectangle with actions, money etc but i want to construct them outside my Window class where i construct the frame and all of the JPanels. Generally now that the player has chosen to play a local game i want to be able to draw and erase on this panel as the game continues. enter image description here

private void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        this.createBufferStrategy(1);
        return;
    }
    
    Graphics g = null;
    
    window.render();
    if (gameState == STATE.MultiPlay) {
        handler.render(g);
        hud.render(g);
    }
    if (gameState == STATE.LocalPlay) {
        handler.render(g);
        hud.render(g);
    }
}

The code i provided is the render method i am using at my game engine class. With my game engine i have made this method circles 10 times per second and i wanted from here to instantiate the Graphics class and then go on with the other class and rendering everything i want to draw over that JPanel.

How can i draw over that JPanel using Graphics or something like that?

Upvotes: 1

Views: 70

Answers (1)

You must use Graphics object like that:

Graphics g= bs.getDrawGraphics();

I think it will be usefull, have a nice day.

PD: If you don't want to do that, you can also override the method paint(Graphcis g) and use the parameter.

Upvotes: 1

Related Questions