首先发布这里,但很长一段时间的读者,一直在搜索,但无法找到一个确切帮助我的问题的帖子。
我正在尝试使用mouselistener创建JLabel的2D网格,并检索单击的JLabel的X / Y位置,但无法找到方法来执行此操作。我尝试了一些我在这个网站上发现的方法,但没有任何工作。
目前我有以下内容......
pcenter.setLayout(new GridLayout(game.getXSize(), game.getYSize()));
pcenter.setBorder(new EmptyBorder(8,8,8,8));
pcenter.setPreferredSize(new Dimension((game.getXSize() * 30), (game.getYSize() * 30)));
gamegrid = new JLabel[game.getXSize()][game.getYSize()];
for ( int i = 0; i < game.getXSize(); i++) {
for (int j = 0; j < game.getYSize(); j++) {
gamegrid[i][j] = new JLabel();
gamegrid[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
gamegrid[i][j].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
}
});
pcenter.add(gamegrid[i][j]);
}
}
&#39;游戏&#39;是一个对象,它包含一个2D数组的对象,我想在其中点击JLabel的相同坐标。 E.G点击gamegrid [2] [5]将联系game.plots [2] [5]。
每当我尝试创建一个变量来存储2和5时,它想要使方法成为FINAL,如果我将该方法放在MouseAdapter()中,它想要制作&#39; i&#39;或者&#39; j&#39; FINAL。
请帮助:)提前感谢。
答案 0 :(得分:0)
想出来了!我会在这里张贴,只是包住别人想知道的。
我在课堂上创建了3个其他变量:
private static Object source;
private static int currentX, currentY;
然后是现在的MouseListener,我添加了以下内容:
for ( int i = 0; i < game.getXSize(); i++) {
for (int j = 0; j < game.getYSize(); j++) {
gamegrid[i][j] = new JLabel();
gamegrid[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
gamegrid[i][j].addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
source = e.getSource(); //added this to get the mouseevent object.
XYsource(); // this is a method to turn the object source
into X and Y coords.
}
});
pcenter.add(gamegrid[i][j]);
}
}
最后将以下方法将Object源转换为X和Y坐标
public static void XYsource() {
int maxX = game.getXSize();
int maxY = game.getYSize();
for(int i = 0; i < maxX; i++) {
for(int j = 0; j < maxY; j++){
if (gamegrid[i][j] == source) {
currentX = i;
currentY = j;
}
}
}
updateXY(); // this is just a method to set text on the screen showing
the X and Y coordinates to test the MouseListener
}