Java 小程序未在 Eclipse 的内置小程序查看器中更新

Java Applet not updating in Eclipse's built in applet viewer

我刚刚了解 java 小程序。我用 drawLine() 在小程序上画了一条线,当我按下 运行 时,它正常编译并使用 Eclipse 的内置小程序查看器显示小程序。这是代码

import java.applet.*;
import java.awt.*;

public class Lab04b {
    public void paint(Graphics g){
    g.drawLine(0, 0, 200, 200);
    }
}

但是,当我注释掉 drawLine() 并重新编译它并 运行 它时,它显示的小程序上面有一行,就好像代码更改时它没有更新一样。这是注释掉的版本:

 import java.applet.*;
 import java.awt.*;

public class Lab04b {
    public void paint(Graphics g){
    //g.drawLine(0, 0, 200, 200);
    }
}

我已经尝试重新打开 Eclipse,但它仍然像第一次一样显示带有一行的小程序 运行。请告诉我如何让 Eclipse 更新内置小程序查看器中的小程序。

您的 Lab04b class 不是小程序:

import java.applet.*;
import java.awt.*;

public class Lab04b {
    public void paint(Graphics g){
    g.drawLine(0, 0, 200, 200);
    }
}

由于 applet class 必须扩展 Applet 或 JApplet,而您的两者都没有。我建议:

  • 让 class 扩展 JApplet
  • 但不要直接在其中绘制。
  • 而是在小程序中显示的 JPanel 的 paintComponent 方法中绘制。
  • 一定要给你的小程序 class 一个 init() 方法,它将保存它的初始化代码。

例如:

import java.awt.Graphics;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;

// an applet class must extend either Applet or JApplet
public class AppletTest extends JApplet {

    // it should have an init() method where it holds its initialization code.
    @Override
    public void init() {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    add(new DrawingPanel());
                }
            });
        } catch (InvocationTargetException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// avoid drawing directly within the applet itself
// but instead draw within a JPanel that is added to the applet
class DrawingPanel extends JPanel {

    // this is the method to draw in
    @Override
    protected void paintComponent(Graphics g) {
        // don't forget to call the super method to do "housekeeping" drawing
        super.paintComponent(g);
        g.drawLine(0, 0, 200, 200);
    }
}
  • 话虽如此,考虑不要学习小程序,因为它们现在很少使用。