我有这些类(class);
public class Car extends JComponent {
}
public class Mazda extends Car {
}
public class Subaru extends Car {
}
在我的汽车类中,我重写了绘制组件的方法
@Override
public void paintComponent(Graphics g) {
//why my planets aren't painted by this method
if (this instanceof Mazda) {
g.fillOval(0, 0, this.getWidth(), this.getHeight());
System.out.println(this.getClass());
}
if (this instanceof Subaru) {
g.setColor(Color.blue);
g.fillOval(0, 0, this.getWidth(), this.getHeight());
System.out.println(this.getClass());
}
}
它可以很好地绘制马自达的实例,但斯巴鲁实例的代码永远不会被调用。看来斯巴鲁并没有继承Car的JComponent?或者为什么不调用 painComponent? Java 新手,所以我可能缺少一些基本的东西
最佳答案
我认为,你的设计有问题,因为,如果你想@Override
来自父类(super class)的方法,好的选择是在基类中执行此操作,例如 Mazda
或Subaru,
特别是,您想要指定不同的行为。在像 Car
这样的抽象类中你可以@Override
常见的方法有Mazda
和Subaru
,并且对于 super 类的 child 这样做并不重要。所以,我认为你可以这样写这个结构:
class Car extends JComponent{
}
class Mazda extends Car{
@Override
public void paintComponents(Graphics g) {
g.fillOval(0, 0, this.getWidth(), this.getHeight());
System.out.println(this.getClass());
}
}
class Subaru extends Car{
@Override
public void paintComponents(Graphics g) {
g.setColor(Color.blue);
g.fillOval(0, 0, this.getWidth(), this.getHeight());
System.out.println(this.getClass());
}
}
然后创建类 Mazda Mazda mazda = new Mazda()
并调用方法:mazda.paintComponent(...
或者使用多态性并创建 e.q. Mazda
像这样:Car mazda = new Mazda();
关于java - 类不继承自扩展至 JComponent 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867886/