Joseph Ruys
Joseph Ruys

Reputation: 11

How to add delay in JPanel

I'm making a pathfinding visualizer in java and I've got everythings down i just need to add a delay so the maze doesn't get completed instantly once i run the program. I tried adding Thread.sleep but my JPanel just doesn't show up when I add it. Does it have something to do with the fact that it's a JPanel and not the usual java program?

Here's my code:

public void AStar(Panel maze, Node start, Node end) {
        // Init all distances with infinity

        for (Node[] node : maze.node) {
            for (Node n : node) {
                n.distance = Integer.MAX_VALUE;
                n.rootDistance = Integer.MAX_VALUE;

                n.manhattanDistance = 2 * (Math.abs(end.col - n.col) + Math.abs(end.row - n.row));
            }
        }
        // Distance to the root itself is zero
        start.distance = 0;

        // Init queue with the root node
        queue.add(start);

        // Iterate over the priority queue until it is empty.
        while(true){
            Thread.sleep(1000);
            if(search() == end) {
                    backtrackPath();
                    break;
                }
            }
        }
public Node search() {
        Node curNode = queue.poll(); // Fetch next closest node
        if (curNode != endPoint && curNode != startPoint) curNode.setAsDiscovered(); // Mark as discovered

        // Iterate over unvisited neighbors
        for (Node neighbor : GetUnvisitedNeighbors(curNode)) {
            // Update root minimal distance to neighbor including manhattan distance
            neighbor.rootDistance = Math.min(neighbor.rootDistance, curNode.rootDistance + 1);
            int minDistance = Math.min(neighbor.distance, neighbor.rootDistance + neighbor.manhattanDistance);
            if (minDistance != neighbor.distance) {
                neighbor.distance = minDistance; // update mininmal distance
                neighbor.parent = curNode; // update best parent
                // Change queue priority of the neighbor since it have became closer.
                if (queue.contains(neighbor)) {
                    queue.remove(neighbor);
                    queue.add(neighbor);
                }
            }
            // Add neighbor to the queue for further visiting.
            if (!queue.contains(neighbor)) {
                queue.add(neighbor);

            }

        }
        return curNode;
    }

I tried using thread.sleep but using this just makes the program wait until it's repeated over and over again and THEN shows up but when the maze is completed too, it doesn't update in real time which I'm trying to achieve here.

Upvotes: 1

Views: 46

Answers (1)

iso53
iso53

Reputation: 72

First of all take a look at here for better understanding of Thread.sleep(). Second as @MadProgrammer suggested generating history of moves and then replaying it will be better. Take a look at this example.

Let's say we want to create a JPanel that changes it's color with a delay. Best way to achieve that would be using SwingWorker. Here is the code for this:

public class MyJPanel extends JPanel {

    private final Color[] colors;

    public MyJPanel(Color[] colors) {
        this.colors = colors;
    }

    public void startColorChange() {
        new ColorChanger().execute();
    }

    private class ColorChanger extends SwingWorker<Void, Color> {
        @Override
        protected Void doInBackground() throws Exception {
            for (Color color : colors) {
                setBackground(color);
                Thread.sleep(1000); // Delay for 1 sec
            }
            return null;
        }
    }
}

And let's initialize this panel and start the color changing process.

MyJPanel myJPanel = new MyJPanel(new Color[]{ 
        Color.RED, 
        Color.BLUE, 
        Color.ORANGE, 
        Color.BLACK, 
        Color.WHITE });
myJPanel.setPreferredSize(new Dimension(200, 200));
panel.add(myJPanel);
myJPanel.startColorChange();

This is the result. My suggestion is take a look at how SwingWorker works. It is probably the think you are looking for. Hope this helps.

Upvotes: 0

Related Questions