Using MouseListener to select a range of cells in

2019-07-20 02:06发布

问题:

Linked post: How to use MouseListener to find a specific cell in a grid

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.

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.

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.

回答1:

use JButtons / JToggleButtons instead of JPanels

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

  • by usage of implemented methods in API

  • use ActionListener for (undecorated) JButton

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



回答2:

Generally, selecting a row or column of cells is the same as selecting a rectangle of cells.

  • The mouseClicked method sets the initial cell.

  • The mouseMoved method sets the current cell that the mouse is in. This is so you can visually indicate to the user what cells have been "selected".

  • The mouseReleased method sets the final cell.

You check to see that the initial cell to the final cell makes up a row or a column. The length of the row or column determines which ship you place. This allows you to place the ships in any order, not just largest to smallest.

You'll have to add a MouseMoveListener to use the mouseMoved method.