使用MouseListener选择网格中的一系列单元格 [英] Using MouseListener to select a range of cells in a grid

查看:81
本文介绍了使用MouseListener选择网格中的一系列单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接的帖子:我正在尝试创建一个由100个单元格组成的10x10网格的战舰游戏. Grid扩展了JPanel,而Cell也扩展了JPanel.早些时候,我在上面的链接中询问了如何实现MouseListener来执行此操作.由于代码都在该页面上,因此我将引用它.

I am trying to create a Battleships game, with a 10x10 grid made up of 100 cells. The Grid extends JPanel and the Cell also extends JPanel. Earlier on I made the link above to ask how to implement a MouseListener to do this. As the code is all on that page, I am just going to refer to it.

有人在我接受的那个链接上发布了一个很好的答案.现在,我可以使用MouseListener来检测网格上任何单元格中的移动,点击等.

Someone posted an excellent answer on that link which I accepted. I can now use MouseListener to detect movement, clicks etc in any cell on the grid.

但是,我遇到了另一个障碍.我正在尝试将船只放置在我的网格上.我暂时忘记了方向(因为我假设所有船只都将被水平放置).第一艘船将占据五个牢房.我想将光标移动到网格上的一个单元格上,并在光标所在的单元格右侧添加另外四个"tail"单元格,并突出显示.如果总共没有五个空闲单元格(可能是因为光标太靠近网格边缘),则这些单元格将变为红色.否则,它们将变为绿色.

However, I've hit another road block. I am trying to place ships on my grid. I am forgetting about orientation for now (as I'm assuming all ships will be placed horizontally). The first ship will take up five cells. I would like to move my cursor onto a cell on the grid and have four other 'tail' cells, to the right of the cell the cursor is over, highlighted as well. If there aren't five free cells in total (perhaps because the cursor is too near the edge of the grid), the cells will turn red. Otherwise, they will turn green.

第一艘船放置后,第二艘船需要放置.它是四个单元格长.因此,当悬停在一个单元格上时,它将具有三个单元格的尾巴",依此类推.

After the first ship is placed, the second will need placing. It is four cells long. Therefore, when hovering over a cell it will have a 'tail' of three cells and so on.

我对如何更改颜色,如何处理方向以及如何从五艘船变为四艘船感到满意.但是,我不知道如何一次选择多个单元格. 有人知道如何实现吗?我很想发表自己尝试过的内容,但事实是,我一无所有.

I am happy with how to change colours, how to handle orientation and how to change from five ships to four ships and so on. However, I have no idea how to select multiple cells at once. Does anybody know how to implement this? I would love to post what I have tried but the truth is, I've got nothing.

推荐答案

使用JButtons/JToggleButtons代替JPanels

use JButtons / JToggleButtons instead of JPanels

  • 您可以使用图标(一个图像分割成所需的数字)

  • you can to use Icon (one Image splitted to desired numbers)

使用API​​中已实现的方法

将ActionListener用于(未修饰的)JButton

use ActionListener for (undecorated) JButton

在JButton

override ButtonModel for implemented mouse events (without / not required to add MouseListner) in JButton

这篇关于使用MouseListener选择网格中的一系列单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆