检查 java swing GUI 中的一系列点击
我正在为国际象棋游戏开发 GUI,我想知道是否有任何方法可以检查一系列点击,例如:用户点击 jPanel,然后用户点击有效移动数组中存在的另一个 jPanel。我知道我可以使用变量来存储某种状态,例如“isSquareClicked = true”或其他东西,但我宁愿不这样做,除非这是唯一的方法......
I'm working on a GUI for a chess game and I was wondering if there's any way to check for a series of clicks, for example: user clicks on jPanel THEN user clicks on another jPanel that exists in valid move array. I know I could use a variable to store some kind of state like "isSquareClicked = true" or something but I'd rather not unless that's the only way...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不认为使用 JPanel 有什么问题。这是我的实现:
首先是一个 ChessSquare,它代表棋盘上的一个单元格:
现在是主板面板:
我们保留一个 JPanel 矩阵来表示棋盘,并使用 ChessSquare 数组来表示当前的移动。在
isValidMove()
中,我们检查当前移动是否完成(两个方块都已被单击,因此移动数组已经有一个元素)。一旦移动完成,我们将重置移动并重新开始。I don't see anything wrong with using JPanels. Here's my implementation:
First a ChessSquare, this represents one cell on the board:
Now the main board panel:
We keep a JPanel matrix to represent the board, and ChessSquare array to represent the current move. In
isValidMove()
we check to see if the current move is complete (both squares have been clicked, thus the move array already has one element). Once a move is complete, we reset the move and start again.我同意 imp - 您可能想要一个 JPanel 并在该面板上绘制所有内容。
话虽这么说,如果有人已经使用 8x8 JPanel 实现了一个棋盘并告诉我使用它,我可能会尝试将 8x8 JPanel 放入 JLayeredPane 中,然后在所有内容之上放置一个透明 JPanel处理所有鼠标点击。
尽管如此,这种方法仍然需要您进行点算术来找出正在单击的单元格,而且我猜测使用 8x8 JPanel 的目的是您希望首先避免进行这种算术。
I agree with imp - You probably want to have a single JPanel and draw everything on that one panel.
That being said, if someone had already implemented a chessboard with 8x8 JPanels and told me to use it, I might try putting the 8x8 JPanels in a JLayeredPane and then putting a single transparent JPanel on top of everything to handle all the mouse clicks.
Still, that approach will require you to do Point arithmetic to figure out what cell is being clicked on, and I'm guessing that the point of using 8x8 JPanels was that you wanted to avoid doing that kind of arithmetic in the first place.
据我所知,Java中没有这样的东西。
但是:
1)据我了解,您使用 8x8 JPanels 的字段来创建游戏字段?恕我直言,这是个坏方法。如果我是你,我会使用一个面板来创建字段 - 通过在其上绘制所有内容(单元格、图形等)。这更简单、创建更快、更容易使用。
2)回到你的问题。如果您有一个字段面板 - 您只需要记住两对坐标:第一次点击在哪里,第二次点击在哪里。在您的情况下 - 单击面板上的 2 个指针就足够了。 ;)
希望这有帮助:)
As I know, there is no such things in Java.
But:
1) As I understand, You use field of 8x8 JPanels to create field for game? IMHO this is bad way. If I were you, I would use one Panel for creating field - by painting all on it(cells, figures, etc). This is more simpler, faster to create, easier to work with.
2) Returning to your question. If you have one panel for field - you only need to remember 2 pairs of coordinates: where was first click, and where was second. In Your case - 2 pointers on panels wich was clicked will be enough. ;)
Hope this help :)