为什么 Java 图形在自定义子类中无法工作?

huangapple go评论55阅读模式
英文:

Why does Java Graphics not work with custom sub classes?

问题

我试图使用Ellipse2D.Double类创建一个专门用于圆的子类。

public class Circle extends Ellipse2D.Double {

    double radius;

    public Circle(double radius) {
        radius = this.radius;
        height = radius * 2;
        width = radius * 2;
        x = 0;
        y = 0;
    }
}

像下面这样填充JPanel不起作用:

JPanel p = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        
        Circle circle1 = new Circle(100);

        g2.draw(circle1);

但像这样做起作用:

g2.draw(new Ellipse2D.Double(0, 0, 100, 100));

为什么会这样?我在构造函数中设置了Ellipse2D的所有字段,也没有收到任何错误消息。所以我不确定为什么它不起作用。

英文:

I am trying to create a subclass just for circles using the Ellipse2D.Double class.

public class Circle extends Ellipse2D.Double{

double radius;

public Circle (double radius){
		radius = this.radius;
        height = radius*2;
        width = radius*2;
		x = 0;
		y = 0;
}

Filling the JPanel like so does not work:

JPanel p = new JPanel() {
		@Override
		public void paintComponent(Graphics g) {
			Graphics2D g2 = (Graphics2D) g;
        
        Circle circle1 = new Circle(100);

        g2.draw(circle1);

but doing it like so does work:

g2.draw(new Ellipse2D.Double(0, 0, 100, 100));

why is this ? I am setting all the fields from Ellipse2D in the constructor and i am not getting any error messages. So i am not sure why it doesnt work.

答案1

得分: 0

你的构造函数是错误的。

radius = this.radius;

这一行将参数变量 radius 设置为 radius 字段的初始值。应该颠倒过来。

this.radius = radius;
英文:

Your constructor is incorrect.

        radius = this.radius;

is setting the parameter variable radius to the initial value of the radius field. It should be the other way around.

        this.radius = radius;

huangapple
  • 本文由 发表于 2020年10月13日 20:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64335618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定