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

MouseClicked() method not working for pathfinding algorithm?

我正在尝试编写一个寻路迷宫算法来尝试将 A* 实现到 JPanel 界面中。代码如下。如您所见,我使用 运行dom 数字生成器 运行domly 生成迷宫方块的颜色。以下是源码的初步实现:

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. 试图在主代码中实现 运行() 方法
  2. 试图在 class
  3. 中实现 运行() 方法
  4. 试图创建私有处理程序class?

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

您必须明确地将鼠标侦听器添加到 JPanel。

public class algo extends JPanel implements MouseListener, MouseMotionListener {

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