英文:
How to draw on a JPanel using Graphics
问题
我正在进行一个项目,我已经制作了一个菜单和一个`JPanel`,但现在我想在`JPanel`上绘图,并在我的游戏中添加一些HUD。
我提供了一张我游戏最终面板的图片,我想在左边添加一个带有玩家头像的蓝色矩形,在右边添加另一个矩形,显示动作、金钱等信息,但我想在构建它们时不使用我的Window类,而是在那里构建框架和所有JPanels。一般来说,既然玩家选择玩本地游戏,我希望能够在游戏进行时在此面板上绘制和擦除。
以下是我在游戏引擎类中使用的渲染方法:
```java
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);
}
}
我提供的代码是我在游戏引擎类中使用的渲染方法。通过我的游戏引擎,我使这个方法每秒循环10次,并且我希望在这里实例化Graphics
类,然后继续进行其他类并绘制我想要在那个JPanel
上绘制的所有内容。
我如何使用Graphics
或类似方法在那个JPanel
上绘制?
<details>
<summary>英文:</summary>
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][1]][1]
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?
[1]: https://i.stack.imgur.com/K0Qpv.png
</details>
# 答案1
**得分**: 1
你必须像这样使用Graphics对象:
Graphics g = bs.getDrawGraphics();
我认为这会很有用,祝你有一个愉快的一天。
附注:如果你不想这样做,你也可以覆盖方法paint(Graphics g),并使用这个参数。
<details>
<summary>英文:</summary>
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.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论