英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论