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);
}
}
我已经看了几个小时的代码,但无法弄清楚出了什么问题。它被复制出教科书。当我跑步时,只显示一个空盒子。它应该显示汽车,一个在左上角,一个在右下角。
答案 0 :(得分:3)
方法paintComponent
拼写错误,因此它不会覆盖超类方法。因此,只调用绘制空白框的默认方法。
通过@Override
注释,有一种方法可以避免这种常见错误。通过将此注释添加到覆盖超类方法或实现接口方法的所有方法,如果您输入方法名称错误,编译器将停止并显示错误,而不是创建难以调试的错误:
@Override
public void paintComponent(Graphics g){
// code here
}