我正在尝试编写寻路迷宫算法,以尝试将A *实现到JPanel接口中。代码如下。如您所见,我使用随机数生成器随机生成迷宫的正方形颜色。以下是原始代码的基本实现:
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()操作时,没有任何反应。我有打印语句尝试对此进行测试,并且每种可能的解决方案都无法解决问题。
关于mouseHandler为什么不响应我的请求的任何其他想法?
答案 0 :(得分:0)
您必须将鼠标侦听器明确添加到JPanel。
public class algo extends JPanel implements MouseListener, MouseMotionListener {
public algo() {
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
// other stuff
}