java 中没有 Graphics2D.draw 方法?

No Graphics2D.draw method in java?

我使用 NetBeans 和 JDK 的最新版本。由于某些原因,没有 Graphics.draw() 方法,尽管 java.awt.geom.Line2Djava.awt.Graphics2D 被导入。如何绘制 Line2D.Double 元素?

Shape pLine;
private void playerDraw(){
    Graphics g2 = getGraphics();
    pLine = new Line2D.Double(px, py, Math.cos(angle)*10+px,Math.sin(angle)*10+py);
    g2.drawRect(px-5, py-5, 10, 10);  
    g2.draw(pLine); //this doesn't compile(cannot find symbol)
}

您错过了在 Class 中声明 pLine 变量:

例如。

public class Example
{

public Line2D.Double pLine;

private void playerDraw(){
    Graphics g2 = getGraphics();
    pLine = new Line2D.Double(px, py,Math.cos(angle)*10+px,Math.sin(angle)*10+py);
    g2.drawRect(px-5, py-5, 10, 10);  
    g2.draw(pLine); //this doesn't compile(cannot find symbol)
}
}

您的主要问题是您将 Graphics 对象当作 Graphics2D 对象来使用,但事实并非如此 Graphics class Java API entry will show you, the Graphics class does not have a draw method, while Graphics2D。我认为您缺少关键行,例如:

Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D) g; // the missing line

但话说回来,您使用 Graphics 不正确,因为您应该避免通过在 Swing 组件上调用 getGraphics() 来获取它,因为这会给您带来不稳定的短期 Graphics 对象,其使用风险会导致短期图像或 NullPointerExceptions,而是您应该在 JComponent 的 paintComponent(Graphics g) 方法中进行绘图。