How to call repaint from another method in an applet?
I'm writing a game (an applet) in java, and I have two threads running. One thread is running in the main class, and the other is a separate class drawing to a graphics variable in a class of public variables for all of the other classes to read. (The main class reads the graphics variable and can paint it (as an image).)
I'd like to be able to call the repaint() method for the main applet from the other class, but I have no idea how to do so because calling the "Main_applet_class".repaint() method results in a "You-can't-call-this-method-from-a-static-conte开发者_高级运维xt" error. Help!
You need a reference to the object that you want to call a method on. One way is to pass the main applet object to the calling class via a constructor parameter in the calling class. Note that this has nothing to do with GUI programming and all to do with basic Java.
For example:
import javax.swing.JApplet;
public class FooApplet extends JApplet {
public void init() {
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}
}
private void createGUI() {
OtherClass otherClass = new OtherClass(this);
}
}
class OtherClass {
private FooApplet fooApplet;
public OtherClass(FooApplet fooApplet) {
this.fooApplet = fooApplet; // now I can call methods on the FooApplet object
}
public void myMethod() {
// ... some code here...
fooApplet.repaint(); // now that I have a valid ref I can call repaint
}
}
精彩评论