【问题标题】:How to call repaint from another method in an applet?如何从小程序中的另一个方法调用重绘?
【发布时间】:2011-08-08 16:44:02
【问题描述】:

我正在用 java 编写一个游戏(一个小程序),我有两个线程正在运行。一个线程在主类中运行,另一个是一个单独的类,绘制到一个公共变量类中的一个图形变量供所有其他类读取。 (主类读取图形变量并可以将其绘制(作为图像)。)

我希望能够从其他类调用主小程序的 repaint() 方法,但我不知道该怎么做,因为调用“Main_applet_class”.repaint() 方法会导致“您不能从静态上下文中调用此方法”错误。救命!

【问题讨论】:

    标签: java multithreading applet repaint


    【解决方案1】:

    您需要对要调用方法的对象的引用。一种方法是通过调用类中的构造函数参数将主小程序对象传递给调用类。请注意,这与 GUI 编程无关,而与基本 Java 有关。

    例如:

    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
       }
    }
    

    【讨论】:

    • 也许我应该包含这个代码:public class InternetHearts extends Applet implements Runnable,MouseListener,MouseMotionListener,KeyListener { //stuff... Thread SPThread; SPGame singleplayer=new SPGame(); //more stuff... public void start() { SPThread=new Thread(singleplayer); SPThread.start(); } //more stuff } public class SPGame implements Runnable { //stuff and a constructor public void run() { //I'd like to call repaint here } }
    • 嗯,是的,我希望我能正确格式化,但我不能在评论中
    • @Evan:将其作为编辑添加到您的原始帖子中,然后在开头使用@hovercraft 发布针对我的评论,以便我知道寻找您的更改。
    猜你喜欢
    • 2014-04-14
    • 2018-04-02
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2010-12-08
    • 2015-06-16
    • 1970-01-01
    • 2013-11-28
    相关资源
    最近更新 更多