[英]Java - Add an instance of an abstract class in another instance
I have this piece of code : 我有这段代码:
public class Profile extends Container{
public Profile(String value) {
Container profilo_1 =new Container();
Container profilo_2 =new Container();
// (1) THIS ADD A BUTTON TO THE MAIN CLASS
this.createButton().setLabel("Modifica Profilo");
// (2) NOW I NEED TO ADD A BUTTON INTO THE INSTANCE OF profilo_2 BUT IT FAILS
profilo_2.add(this.createButton());
this.add(profilo_1);
this.add(profilo_2);
}
}
the point (2) fails, because it said that im about to adding a child to this container, but it is owner already by a container... 点(2)失败了,因为它说即时消息即将向该容器添加一个子对象,但是它已经是容器的所有者了...
In fact, if i do this : 实际上,如果我这样做:
ILabel label=new ILabel();
profilo_2.add(label);
it said to me that ILabel() is abract and cannot be instantiated! 它告诉我,ILabel()是abract,无法实例化!
How can I fix it? 我该如何解决? Cheers to everybody :)
为大家加油:)
Try changing to 尝试更改为
Button button2 = this.createButton();
button2.setLabel("EDIT");
profilo_2.add(button2);
By the way this has nothing to do with abstract classes, from what I see 顺便说一下,这与抽象类无关,据我所知
EDIT : Though you say that #1 "adds a button to the main class", so does that mean that createButton() does this.add(button) ? 编辑 :尽管您说#1“向主类添加了一个按钮”,但这是否意味着createButton()做到了this.add(button)? If so then you should probably change that function so that isn't done every time you create a button.
如果是这样,那么您可能应该更改该功能,这样就不会在每次创建按钮时都这样做。
The problem is probably that when you create a button with "this.createButton", that button has its parent set to "this" (in this context), and when you try to add it to profilo_2, it throws an error. 问题可能是当您使用“ this.createButton”创建按钮时,该按钮的父级设置为“ this”(在此上下文中),并且当您尝试将其添加到profilo_2时,它将引发错误。 Instead you should createButton on profilo_2 directly, then the parent will be the correct one (and perhaps you won´t have to add() it either?)
相反,您应该直接在profilo_2上创建createButton,然后父级才是正确的(也许您也不必对它进行add()吗?)
疯狂地猜测,因为这取决于您的代码...试试这个(除非Piotr说了什么)
profilo_2.add(profilo_2.createButton());
Probably, setLabel()
returns something which cannot be passed to Container::add(..)
. setLabel()
可能返回无法传递给Container::add(..)
。 Please provide your code for Container
请提供您的
Container
代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.