在简单的 Java Swing 游戏中使用哪些容器/图形组件?
我正在使用 Java + Swing 创建一个简单的迷宫游戏。游戏在屏幕上绘制一个随机迷宫,在中间放置一个图形,然后玩家通过使用箭头键移动图形来找到出路。目前,我使用纯背景并使用 Graphics.drawLine() 绘制迷宫的墙壁。我在 .gif 文件中有一张自定义的图形图片,我将其作为 BufferedImage 对象加载。
然而,我希望玩家一次只能看到迷宫的一部分,并且当玩家四处移动时,屏幕应该跟随游戏中的人物移动。我计划通过在创建整个迷宫时创建一个 Image 对象来实现此目的,然后在图形的当前位置周围“切割”一个正方形并使用 Graphics.drawImage() 显示它。不过,我对 Swing 很陌生,我无法弄清楚如何在不重新绘制整个迷宫的情况下在迷宫“上方”的不同位置绘制图形。我应该为迷宫使用哪个容器/组件,然后为人物使用哪个容器/组件来实现这一目标?
I'm creating a simple labyrinth game with Java + Swing. The game draws a randomized labyrinth on the screen, places a figure in the middle, and the player is then supposed to find the way out by moving the figure with arrow-keys. As for now, I'm using a plain background and drawing the walls of the labyrinth with Graphics.drawLine(). I have a custom picture of the figure in a .gif file, which I load as a BufferedImage object.
However, I want the player to see only part of the labyrinth at a time, and the screen should follow the figure in the game, as the player moves around. I'm planning to do this by creating an Image object of the whole labyrinth when it is created, and then "cutting" a square around the current position of the figure and displaying this with Graphics.drawImage(). I'm new with Swing though, and I can't figure out how to draw the figure at different positions "above" the labyrinth without redrawing the whole thing. Which container/component should I use for the labyrinth and then for the figure to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用包含图标的 JLabel。然后你只需使用 label.setLocation() 来移动图像。 Swing 足够智能,可以重新绘制旧区域(图像所在的位置),然后在新位置绘制图像。
您应该能够使用单个 JPanel 来完成此操作。您对面板的自定义绘画将绘制迷宫。作为子组件添加的标签将绘制在迷宫的顶部。
查看此帖子的最后一个条目,其中包含构建迷宫,它还支持随着玩家移动而滚动迷宫。
Use a JLabel containing an icon. Then you just use label.setLocation() to move the image. Swing is smart enough to repaint the old area (where the image was) and then paint the image at its new location.
You should be able to do this with a single JPanel. Your custom painting of the panel will paint the maze. The the label which is added as a child component will be painted on top of the maze.
Check out the last entry of this posting which contains an interesting approach for building the maze and it also supports scrolling of the maze as the player moves.
我认为玻璃板就是您正在寻找的组件:它是一种放置在框架上的玻璃。您在其上绘制的所有内容都会覆盖后面的内容..因此您可以轻松实现效果,而无需担心剪切原始图像..请参阅 这里!
I think that the glass pane is the component you are looking for: it's a sort of glass placed onto the frame. Everything you draw on it will cover what's behind.. so you can achieve easily the effect without caring about clipping the original image.. see here!
您可以查看
JLayeredPane
,在如何使用分层中讨论窗格和这个问题。You might look at
JLayeredPane
, discussed in How to Use Layered Panes and in this question.