gpt4 book ai didi

java - 如何在 JPanel 上绘制图像

转载 作者:行者123 更新时间:2023-11-30 04:09:47 26 4
gpt4 key购买 nike

我有一个战舰游戏,我试图在 Grid 对象上绘制船只、命中和未命中。 Grid 是具有许多Blocks 的 JPanel 实例。 Blocks 也是 JPanel,但是是 Grid 的属性。船只被绘制在网格上但位于 block 下方。是否可以在 block 上绘制?我尝试了玻璃板,但效果不太好。还有其他解决方案吗?

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

最佳答案

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

是的,一种不推荐但有时有用的方法是使用扩展的 JPanel 并覆盖 paint(Graphics g) 函数:

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
}

}

或者,您可以考虑使用 JLayeredPane 来处理包含在目标面板(网格)层上方绘制的图像的面板。查看How to Use Layered Pane

关于java - 如何在 JPanel 上绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19911940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com