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

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

Why does Java Graphics not work with custom sub classes?

问题

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

  1. public class Circle extends Ellipse2D.Double {
  2. double radius;
  3. public Circle(double radius) {
  4. radius = this.radius;
  5. height = radius * 2;
  6. width = radius * 2;
  7. x = 0;
  8. y = 0;
  9. }
  10. }

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

  1. JPanel p = new JPanel() {
  2. @Override
  3. public void paintComponent(Graphics g) {
  4. Graphics2D g2 = (Graphics2D) g;
  5. Circle circle1 = new Circle(100);
  6. g2.draw(circle1);

但像这样做起作用:

  1. 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.

  1. public class Circle extends Ellipse2D.Double{
  2. double radius;
  3. public Circle (double radius){
  4. radius = this.radius;
  5. height = radius*2;
  6. width = radius*2;
  7. x = 0;
  8. y = 0;
  9. }

Filling the JPanel like so does not work:

  1. JPanel p = new JPanel() {
  2. @Override
  3. public void paintComponent(Graphics g) {
  4. Graphics2D g2 = (Graphics2D) g;
  5. Circle circle1 = new Circle(100);
  6. g2.draw(circle1);

but doing it like so does work:

  1. 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

你的构造函数是错误的。

  1. radius = this.radius;

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

  1. this.radius = radius;
英文:

Your constructor is incorrect.

  1. radius = this.radius;

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

  1. 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:

确定