Canvas not being drawn
I'm creating an applet where a player can play a game against an AI player. I'd like to create the option of having 2 AI's play against eachother. This works, but for some reason a graph which works fine in Human vs AI doesn't work in AI vs AI.
I've created a subclass of Canvas that should draw a graph somewhere in the applet. I've added this Canvas to my Applet (this.add(canvas, BorderLayout.WEST)).
This works fine when I play with the player vs the AI. When two AI's play against eachother, the canvas is not drawn. I suspect that this is because when two AIs play against eachother, the program never returns to the java runtime. When a human player plays against the AI, there is time in which non of my code is being executed, because the applet is awaiting new input from the player. When the AI plays against another AI this never happens. I thought at first that this problem was because paint() was never called in the latter case, but that's not true. paint() is being called, but for some reason the components add()ed to the applet are not being redrawn, or are not visible for some other reason.
Is there any chance someone can point me into the direction of the problem with just this description of the problem?
You're almost certainly executing your program logic on the EDT, thus blocking it and effectively preventing it from doing anything else -- like repainting the components.
This tutorial is for Swing, but even if your applet is a awt Applet and not a JApplet, much of it is applicable.
Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI with JFC/Swing)
Thanks a lot, I'm pretty sure that is indeed the problem!
Ok, I've partly rewritten my applet to be a JApplet and have organised the threads as explained in the tutorial you posted.
My question is this: how do I "send a message" from the EDT to the worker thread? I want to do this when a button is pressed (code running in the EDT) and do it in a threadsafe manner.
Is it safe to set a boolean without a lock? How do I send larger messages between threads?
What's the worker thread doing, running a loop? If so you could interrupt the loop the way you've obviously thought of, by setting a boolean field. Or if you're using a SwingWorker, it has a cancel() method (to be used with caution -- check the API).