我刚刚学习java applet。我用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 类不是 Applet:
import java.applet.*;
import java.awt.*;
public class Lab04b {
public void paint(Graphics g){
g.drawLine(0, 0, 200, 200);
}
}
因为 applet 类必须扩展 Applet 或 JApplet,而您的类则两者都不扩展。我建议:
- 让类扩展 JApplet
- 但不要直接在其中绘制。
- 而是在小程序中显示的 JPanel 的
paintComponent
方法中进行绘制。 - 请务必为您的小程序类提供一个
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);
}
}
- 话虽如此,请考虑不要学习小程序,因为它们现在很少使用。
关于Java Applet 未在 Eclipse 的内置 applet 查看器中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32262503/