JavaFX边缘方块禁止切换功能失效,事件处理方法排查请求
Fixing Edge Tile Toggle Restriction in JavaFX Map
Hey there! Let's figure out why your handle method is letting all tiles (including edge ones) toggle states. The root issue almost always comes down to missing a check for whether the clicked tile is on the map's boundary.
First, let's look at a common problematic handle method:
@Override public void handle(MouseEvent event) { Tile clickedTile = (Tile) event.getSource(); // No check for edge tiles—toggles every tile clicked clickedTile.toggleState(); }
This code directly toggles the tile's state without verifying if it's an edge tile. That's why all tiles are responding to clicks.
How to fix it: Add edge tile validation
You need to add a condition that checks if the clicked tile is on the map's edge. To do this, you'll need:
- The clicked tile's position (x/y coordinates in your grid)
- The total number of rows and columns in your map
Here's the corrected handle method:
@Override public void handle(MouseEvent event) { Tile clickedTile = (Tile) event.getSource(); int tileX = clickedTile.getX(); // Get tile's column position int tileY = clickedTile.getY(); // Get tile's row position // Replace these with your actual map dimensions int totalColumns = yourMap.getTotalColumns(); int totalRows = yourMap.getTotalRows(); // Check if the tile is on any edge boolean isEdgeTile = (tileX == 0) || (tileX == totalColumns - 1) || (tileY == 0) || (tileY == totalRows - 1); // Only toggle if it's NOT an edge tile if (!isEdgeTile) { clickedTile.toggleState(); } }
Quick notes to adjust this to your code:
- Make sure your
Tileclass has workinggetX()andgetY()methods that return its position in the grid (double-check you aren't mixing up rows and columns!). - If your map is stored in a 2D array, you can get dimensions like this:
int totalRows = mapArray.length; int totalColumns = mapArray[0].length; - If you've marked edge tiles with a flag (like a
boolean isEdgefield inTile), you can simplify the check toif (!clickedTile.isEdge())instead.
内容的提问来源于stack exchange,提问作者Java Programer
相关产品推荐
相关产品推荐

