Originally posted by Balasubramanian Chandrasekaran:
Is there a restriction that we can add component only once. Can anyone explain me this behaviour
Yes, there is exactly this restriction. If you try to add a Component to a second Container, it will automatically be removed from the first Container first. There are good reasons for this, but they are easiest to understand if you think of text fields and buttons instead of menu items. Menu items do behave the same as other Components, though.
One thing you can try is instead of attempting to add a JMenuItem multiple places, instead add an Action to them. An Action isn't a Component, but can be added directly to a JMenu (in which case a JMenuItem is created for you behind the scenes).
I just tried one more implementation in which i tried to add same menuitem on different menu but in that one also i am able to view menuitem on the second menu only
Code which i tried for that implementation is
But you're still adding menuItem to two different Containers. It should appear correctly if you just do:
If you want to take my Action suggestion it would look something like:
I just thought of reusing the same object.Can you explain me why that restriction is there (in detail). In the mean while i will try to implement your Action on my code. [ April 17, 2008: Message edited by: Balasubramanian Chandrasekaran ]
posted 10 years ago
Originally posted by Balasubramanian Chandrasekaran: I just thought of reusing the same object.Can you explain me why that restriction is there (in detail).
If you just want to be convinced that it is true, take a look at the source for the Container.add() methods. They eventually delegate to Container.addImpl(), which does this:
If you want to understand the why of this, consider that an instance of Component has a number of properties that can be accessed with methods such as getBounds(), getLocation(), getX(), getY(), isFocusOwner(), and getParent(). How would you suggest these methods be implemented for Components that have somehow been added to more than one Container? [ April 17, 2008: Message edited by: Brian Cole ]