我有一个战舰游戏,我试图在Grid对象上绘制船只、命中和未命中。Grid是 JPanel 的一个实例,其中包含许多Blocks. Blocks也是 JPanel,但它们是Grid. 这些船被绘制在网格上,但在块下。是否可以在积木上绘制?我尝试了玻璃窗格,但效果不太好。还有其他解决方案吗?

是否可以在积木上绘制?我尝试了玻璃窗格,但效果不太好。还有其他解决方案吗?
是的,一种不推荐但有时有用的方法是使用扩展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
}
}
或者,您可以考虑使用在目标 panel(Grid)的图层JLayeredPane上方包含您绘制的图像的 Panel 。查看How to Use Layered Pane
Blocks也是JPanels但是是网格的属性。船只正在网格上绘制,但在Blocks.
有一种偷偷摸摸的方法来实现它,但您可能需要将基本布局更改为GridBagLayout.
基本上,您希望将每个添加Block到自己的单元格中,但GridBagLayout允许您添加可以扩展列和/或行的组件,允许添加扩展超过Blocks.
当然,这假设您的船只和效果基于组件