gpt4 book ai didi

java - MouseClicked() 方法不适用于寻路算法?

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:39 27 4
gpt4 key购买 nike

我正在尝试编写一个寻路迷宫算法,以尝试将 A* 实现到 JPanel 接口(interface)中。代码如下。如您所见,我使用随机数生成器随机生成迷宫方 block 的颜色。以下是源代码的基本实现:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
import java.util.Random;


public class algo extends JPanel
implements MouseListener, MouseMotionListener
{


static int[][] map;

public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);

//draw a for loop to print the map
for (int i = 0; i < map.length; i++) {
for(int j = 0; j < map[i].length; j++) {
g.setColor(Color.WHITE);

if(map[i][j] == 1) {
g.setColor(Color.BLACK);
}

g.fillRect(j * 20, i * 20, map[i].length * 20, map.length *20);

}
}

}

public static void main(String[] args) {
System.out.println("Welcome to the A* Shortest Pathfinding Robot Program \n *****"
+ "**************************"
+ "********************\n");
System.out.println("How large would you like your graph to be? Enter 2 consecutive numbers, one for length, one for width:\n");
Scanner sizeScan = new Scanner(System.in);
int length = sizeScan.nextInt();
int width = sizeScan.nextInt();
map = new int[length][width];
Random gridGenerate = new Random();
for(int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
map[i][j] = gridGenerate.nextInt(2);
System.out.print(map[i][j] + " ");
}
System.out.println();

}
JFrame f = new JFrame("A Star Pathfinder");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
algo star = new algo();
f.add(star);
f.setSize(length * 20, width * 20);
f.setVisible(true);

}

@Override
public void mouseDragged(MouseEvent e) {}

@Override
public void mouseMoved(MouseEvent e) {}

@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Successfully Clicked");
if (SwingUtilities.isLeftMouseButton(e)) {
System.out.println("This is the left mouse button that is clicked");
}
}



@Override
public void mouseEntered(MouseEvent e) {}

@Override
public void mouseExited(MouseEvent e) {}

@Override
public void mousePressed(MouseEvent e) {}

@Override
public void mouseReleased(MouseEvent e) {}

}

当我运行 main() 方法时,我能够成功生成迷宫:

Here is the "Maze" Generated from the code

但是,当我尝试在迷宫上实现 MouseClick() 操作时,没有任何反应。我有打印语句来尝试测试这一点,并且每种可能的解决方案都没有解决问题。

  1. 尝试在主代码中实现 run() 方法
  2. 尝试在类中实现 run() 方法
  3. 尝试创建私有(private)处理程序类?

关于为什么 mouseHandler 没有响应我的请求还有其他想法吗?

最佳答案

您必须显式地将鼠标监听器添加到 JPanel。

public class algo extends JPanel implements MouseListener, MouseMotionListener {

public algo() {
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
// other stuff
}

关于java - MouseClicked() 方法不适用于寻路算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com