Search code examples
javagraphicsappletgraphics2d

What is wrong with my applet code?


I am following a tutorial on applets on Youtube. My code looks exactly the same as the tutorial's does, but the background does not turn pink and Eclipse tells me there are errors in implements MouseListener and g2.draw(line); What did I do wrong? Click here for the video and here is my code:

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);

}
}

EDIT: The error at g2D.draw(line); says The method draw(Line2D.Double) is undefined for the type Graphics. I changed g2D.drawLine to g2D.draw I also fixed the implements typo. The background is still not pink, despite the absence of an error and everything else works. What can I do to fix the pinkness and g2D.draw?


Solution

  • You have a typographical error. implements not implemets:

    public class clean extends JApplet implements MouseListener{


    Also you have declared g2D with the wrong type (Graphics vs Graphics2D). In other words, instead of Graphics g2D = (Graphics2D) g; you need to use Graphics2D g2D = (Graphics2D) g;

    Once you make the above change, you will be able to invoke the g2D.draw() methods using the various 2D classes as parameters.


    Also you have overridden the paint() method but you have not included a call to super.paint() - this should be the first line in your paint() method. Once you do this the background color should be rendered correctly (because it is handled by the base class, JApplet)