actionPerformed не работает для таймера - PullRequest
0 голосов
/ 10 мая 2018

В настоящее время я пытаюсь написать код, который включает в себя текстовый документ 1с, 0с, 2 и 3, который будет выполнять роль лабиринта, 2 - начало и 3 - конец, а также использовать таймер и метод поиска для решения.сказал лабиринт.В настоящее время моя программа будет запускаться и правильно отображать лабиринт, но он не решит лабиринт.Я выполнил отладку, и она перейдет к классу TimerListener, но не к методу actionPerformed, и я не могу понять, почему.Вот копия моего кода:

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.Timer;

public class homework11and12 extends JFrame {
    private final int width = 1000;
    private final int height = 700;
    private JFrame frame;
    private DrawComponent component;
    private JPanel panel;
    private final int exitBlock = 3;
    private final int charBlock = 2;
    private final int emptyBlock = 0;
    private final int wallBlock = 1;
    private final int visitedBlock = 4;
    private final int moveRight = 5;
    private final int moveDown = 6;
    private final int moveUp = 7;
    private final int moveLeft = 8;
    private int[][] maze;
    private static int startX = 0;
    private static int startY = 0;
    private ActionListener listener;

    public homework11and12() {
        this.setSize(width, height + 100);
        maze = new int[7][10];
        loadMaze("test", maze);
        this.component = new DrawComponent(maze);
        this.add(this.component);
        listener = new TimerListener();
        final int DELAY = 100;
        Timer t = new Timer(DELAY, listener);
        t.start();
    }

    public JPanel addPanel() {
        panel = new JPanel();
        component = new DrawComponent(maze);
        panel.add(component);
        panel.setVisible(true);
        return panel;
    }

    public static void loadMaze(String filename, int[][] maze)  {
        try {
            File file = new File(filename);
            Scanner in = new Scanner(file);
            int y = 0;
            while(y < 7) {
                for (int x = 0; x < 10; x++) {
                    try {
                        maze[y][x] = in.nextInt();
                        if( maze[y][x] == 2) {
                            startX = x;
                            startY = y;
                        }
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }   
                y++;
            }
        }
        catch (FileNotFoundException e) {
            System.out.println("Error in finding file.");
        }
    }

    private ArrayList<Integer> findSolution(int[][] board,int posx, int posy) {  
        ArrayList<Integer> moveList = null;
        if(posx+1<width) {
            if(board[posy][posx] == exitBlock) {
                moveList = new ArrayList<Integer>();;
                moveList.add(moveRight);
                repaint();
                return moveList;
            }
            else if (board[posy][posx] == emptyBlock) {
                moveList = new ArrayList<Integer>();
                moveList.add(moveRight);
                repaint();
                int[][] newBoard = arrayCopy(board);
                newBoard[posy][posx+1] = visitedBlock;
                ArrayList<Integer> result = findSolution(newBoard, posx+1, posy);
                if (result == null) {
                    moveList = null;
                }
                else {
                    moveList.addAll(result);
                    return moveList;
                }
            }
        }
        else if (posy + 1< height) {
            if(board[posy][posx] == exitBlock) {
                moveList = new ArrayList<Integer>();
                moveList.add(moveDown);
                repaint();
                return moveList;
            }
            else if (board[posy+1][posx] == emptyBlock) {
                moveList = new ArrayList<Integer>();
                moveList.add(moveDown);
                repaint();
                int[][] newBoard = arrayCopy(board);
                newBoard[posy+1][posx] = visitedBlock;
                ArrayList<Integer> result = findSolution(newBoard, posx, posy + 1);   
                if (result == null) {
                    return null;
                }
                else {
                    moveList.addAll(result);
                    return moveList;
                }
            }
        }
        else if(posy - 1 >= 0) {
            if(board[posy-1][posx] == exitBlock) {
                moveList = new ArrayList<Integer>();
                moveList.add(moveDown);
                repaint();
                return moveList;
            }
            else if (board[posy-1][posx] == emptyBlock) {
                moveList = new ArrayList<Integer>();
                moveList.add(moveDown);
                repaint();
                int[][] newBoard = arrayCopy(board);
                newBoard[posy-1][posx] = visitedBlock;
                ArrayList<Integer> result = findSolution(newBoard, posx, posy-1);
                if (result == null) {
                    return result;
                }
                else {
                    moveList.addAll(result);
                    return moveList;
               }
            }
        }
        else if(posx - 1 >= 0) {
            if(board[posy][posx-1] == exitBlock) {
                moveList = new ArrayList<Integer>();
                moveList.add(moveLeft);
                repaint();
                return moveList;
            }
            else if(board[posy][posx-1] == emptyBlock) {
                moveList = new ArrayList<Integer>();
                moveList.add(moveLeft);
                repaint();
                int[][] newBoard = arrayCopy(board);
                newBoard[posy][posx - 1] = visitedBlock;
                ArrayList<Integer> result = findSolution(newBoard, posx-1, posy);
                if (result == null) {
                    moveList = null;
                }
                else {
                    moveList.addAll(result);
                    return moveList;
               }
            }
        }
        return moveList;
    }

    private int[][] arrayCopy(int[][] array) {
        if(array == null) {
            return null;
        }
        int[][] newArray = new int[array.length][];
        for(int r = 0; r <array.length; r++) {
            newArray[r] = array[r].clone();
        }
        return newArray;
    }

    class DrawComponent extends JComponent {
        private int[][] maze;
        private DrawComponent(int[][] maze) {
            this.maze = maze;
        }
        private static final long serialVersionUID = 1L;

        public void paintComponent(Graphics g) {
        int y = 0;
            while (y < 7) {
                 for (int x = 0; x < 10; x++) {
                    if (maze[y][x] == 1) {
                        g.setColor(Color.BLACK);
                        g.fillRect(x * 100,  y* 100, 100, 100);
                    }
                    else if(maze[y][x] == 2) {
                        g.setColor(Color.ORANGE);
                        g.fillRect(x * 100, y * 100, 100, 100);
                    }
                    else if(maze[y][x] == 3) {
                        g.setColor(Color.RED);
                        g.fillRect(x * 100, y * 100, 100, 100);
                    }
                }
                y++;
            }
        }
    }
        class TimerListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                findSolution(maze, startX, startY);
            }
    }
}

Класс TimerListener находится в нижней части кода.Это проблема с тем, где я запускаю таймер?Несколько вопросов, на которые уже были даны ответы, были похожими и говорили, что проблема в том, что таймер так и не запустился, но я почти уверен, что мой таймер запускается.

Редактировать: вот мой метод main ()

import java.awt.BorderLayout;
import java.io.FileNotFoundException;
import java.util.Arrays;

import javax.swing.JFrame;

public class homeworkTest extends homework11and12 {

    public static void main(String[] args) throws FileNotFoundException {
        homework11and12 test = new homework11and12();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        test.setVisible(true);
        test.setTitle("Maze");
    }
}

Спасибо

...