java - What is wrong with my GUI program -
import java.awt.graphics2d; import java.awt.rectangle; import java.awt.geom.point2d; import java.awt.geom.ellipse2d; import java.awt.geom.line2d; public class car { private int xleft; private int ytop; public car(int x, int y){ xleft =x; ytop=y; } public void draw(graphics2d g2){ rectangle body = new rectangle(xleft, ytop+10, 60, 10); ellipse2d.double fronttire= new ellipse2d.double(xleft+10, ytop+20, 10, 10); ellipse2d.double reartire= new ellipse2d.double(xleft+40,ytop+20,10,10); point2d.double r1 = new point2d.double(xleft+10,ytop+10); point2d.double r2 = new point2d.double(xleft+20,ytop); point2d.double r3 = new point2d.double(xleft+40,ytop); point2d.double r4 = new point2d.double(xleft+50,ytop+10); line2d.double frontwindshield = new line2d.double(r1,r2); line2d.double rooftop = new line2d.double(r2,r3); line2d.double rearwindshield = new line2d.double(r3,r4); g2.draw(body); g2.draw(fronttire); g2.draw(reartire); g2.draw(frontwindshield); g2.draw(rooftop); g2.draw(rearwindshield); } } import java.awt.graphics; import java.awt.graphics2d; import javax.swing.jcomponent; public class carcomponent extends jcomponent { public void paintcompnent(graphics g){ graphics2d g2 = (graphics2d) g; car car1 = new car(0,0); int x = getwidth()-60; int y = getheight()-30; car car2 = new car(x,y); car1.draw(g2); car2.draw(g2); } } import javax.swing.jframe; public class carviewer { public static void main(string[] args) { jframe frame = new jframe(); frame.setsize(400,500); frame.settitle("two cars"); frame.setdefaultcloseoperation(jframe.exit_on_close); carcomponent component = new carcomponent(); frame.add(component); frame.setvisible(true); } }
i have looked @ code hours, can't figure out wrong. copied right out of textbook. when hit run, empty box shows up. supposed show cars, 1 on top left, 1 on bottom right.
the method paintcomponent
misspelled , not override superclass method. hence, default method draws blank box called.
there way avoid common bug down road, @override
annotation. adding annotation methods either override superclass method or implement interface method, compiler stop error if mistype method name, rather creating difficult-to-debug error:
@override public void paintcomponent(graphics g){ // code here }
Comments
Post a Comment