【问题标题】:What is wrong with my applet code?我的小程序代码有什么问题?
【发布时间】:2015-06-04 05:25:37
【问题描述】:

我正在关注 Youtube 上的小程序教程。我的代码看起来和教程的完全一样,但是背景没有变成粉红色,Eclipse 告诉我implements MouseListenerg2.draw(line); 有错误我做错了什么? Click here 观看视频,这是我的代码:

package applets1;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

import javax.swing.JApplet;

public class clean extends JApplet implements MouseListener{

public void start(){



}

public void init(){

    setBackground(Color.pink);
    addMouseListener(this);

}

public void paint(Graphics g){

    Graphics g2D = (Graphics2D) g;

    g.drawString("WAZZUP", 100, 90);
    g.drawRect(100, 100, 400, 400);

    Point2D.Double topLeft = new Point2D.Double(0.0, 25.0);
    Point2D.Double topRight = new Point2D.Double(100.0, 25.0);

    Line2D.Double line = new Line2D.Double(topLeft, topRight);

    g2D.draw(line);

}
}

编辑:g2D.draw(line); 的错误是The method draw(Line2D.Double) is undefined for the type Graphics。我将g2D.drawLine 更改为g2D.draw 我还修正了implements 错字。尽管没有错误并且其他一切正常,但背景仍然不是粉红色。我该怎么做才能修复粉红色和g2D.draw

【问题讨论】:

  • "... and Eclipse tells me there are errors in..." -- 假设您可能想向我们显示错误消息,不是吗?
  • 还有更严肃的一点——不要做小程序或教程来教他们。并且永远不要在顶级窗口的绘制方法中绘制,并且您应该几乎总是在覆盖内部调用超级绘制方法。
  • 如果您遇到错误,请在您的问题中显示这些错误,因为它们经常解释问题。此外,您的代码中出现了一些拼写错误,例如 implemets 而不是 implements
  • @HovercraftFullOfEels 为什么我不应该做小程序?
  • @Caders117: one reasonanother

标签: java graphics applet graphics2d


【解决方案1】:

您有一个印刷错误。 implements 未实现:

public class clean extends JApplet implements MouseListener{


您还使用错误的类型声明了 g2D(GraphicsGraphics2D)。换句话说,而不是 Graphics g2D = (Graphics2D) g;你需要使用 Graphics2D g2D = (Graphics2D) g;

完成上述更改后,您将能够使用各种 2D 类作为参数来调用 g2D.draw() 方法。


您还覆盖了paint() 方法,但没有包含对super.paint() 的调用——这应该是paint() 方法中的第一行。一旦你这样做了,背景颜色应该被正确渲染(因为它是由基类处理的,JApplet

【讨论】:

  • 并致电super.paint
  • @MadProgrammer 很好,我会将其纳入我的回答中,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 2021-07-04
  • 2011-07-28
相关资源
最近更新 更多