我在Java applet中绘制多边形时遇到问题。我不明白这段代码有什么问题。我有一个名为DrawPoly的类,其中包含:
import java.awt.*;
import java.awt.geom.Point2D;
import java.applet.Applet;
import java.util.Vector;
public class DrawPoly extends Applet{
Polygon poly;
public void init(Graphics g){
Polygon poly=new Polygon();
poly.addPoint(60,100);
}
public void paint(Graphics g)
{
Graphics2D gg;
gg=(Graphics2D) g;
System.out.println("number is"+ poly.npoints);
}
}
我不明白为什么以下代码不起作用。我想创建一个全局多边形,在init中初始化它,然后进行一些2D转换,例如在paint中旋转。我错过了什么?我只添加了一个点来查看初始化是否为corect。我不想在paint()中初始化多边形,因为我可能想要使用repaint(),每次调用repaint()时都会初始化多边形。如果你能帮我的话。非常感谢。
答案 0 :(得分:2)
/* <applet code='DrawPoly' width=200 height=110></applet> */
import java.awt.*;
import java.applet.Applet;
public class DrawPoly extends Applet {
Polygon poly;
// init(Graphics) is not an applet method
//public void init(Graphics g){
@Override
public void init() {
// this declaration is creating a variable local
// to the init() method
//Polygon poly=new Polygon();
poly=new Polygon();
poly.addPoint(60,100);
// at least add a 2nd point!
poly.addPoint(160,60);
}
public void paint(Graphics g) {
Graphics2D gg;
gg=(Graphics2D) g;
System.out.println("number is"+ poly.npoints);
// the Polygon is never painted!
gg.setColor(Color.BLACK);
gg.drawPolygon(poly);
}
}