我正在创建一个Hex游戏,需要检测对应于网格内特定六边形的点击,以便更改该多边形的颜色。我认为这应该在扩展JPanel的类中发生。该代码显示了如何生成网格。
我已经尝试过使用MouseListener / MouseMotionListener进行实验,但是没有任何令人满意的结果。
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JPanel;
public class TestPanel extends JPanel{
private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
private int x = (int)(screen.getWidth()) / 61;
private int y = (int)(screen.getHeight()) / 41;
private final int SIZE = 11;
private int xShift = 0;
private Polygon[][] grid = new Polygon[SIZE][SIZE];
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 1; i <= SIZE; i++)
{
int[] yPoly = {(2 * i) * y, (2 * i - 1) * y, (2 * i) * y, (2 * i + 1) * y, (2 * i + 2) * y, (2 * i + 1) * y};
for(int j = 1; j <= SIZE; j++)
{
int[] xPoly = {(2 * j - 1) * x + xShift, (2 * j) * x + xShift, (2 * j + 1) * x + xShift, (2 * j + 1) * x + xShift, (2 * j) * x + xShift, (2 * j - 1) * x + xShift};
grid[i - 1][j - 1] = new Polygon(xPoly, yPoly, xPoly.length);
g.drawPolygon(grid[i - 1][j - 1]);
}
xShift += x;
}
}
}