Search code examples
javaswingjcomponent

Where does Java copy and store objects when .add'ing them to a Swing component?


The overall question is - where does Java store component (buttons, menu items, etc.) objects when they're added to something like a JFrame, JPanel, JMenu? While digging through the documentation I saw something saying they're stored in a list, but I'm still trying to find specific information on that implementation by digging through Oracle's docs. Could someone who already understands it help me to understand?

While moving through Oracle's Java Tutorials I noticed that a single identifier is re-used to create objects of the same type. For example, this creates two separate buttons:

JPanel buttonPnale = new JPanel("Making some buttons");
JButton buttonMaker;

buttonMaker = new JButton("Left button", blueBurstIcon);
buttonPanel.add(buttonMaker);

buttonMaker = new JButton("Right button", orangeBurstIcon);
buttonPanel.add(buttonMaker);

Typically I would have thought I needed to do this:

JButton buttonOne = new JButton("Left button", blueBurstIcon);
JButton buttonTwo = new JButton("Right button", orangeBurstIcon);

Creating a separate identifier to go with each separate object.

Obviously the objects in the first snippet of code are being saved somewhere, I'm just trying to find out where. It must be when I call .add that they're copied - but where are they copied to? If they're added to a JPanel, are they copied into a data structure the JPanel contains? Or to a data structure in part of the JFrame to which the JPanel has been added?


Solution

  • A JPanel inherits from java.awt.Container, which maintains an internal list of client components (your JButtons in this case). You can find this list in the source code of Container:

    /**
     * The components in this container.
     * @see #add
     * @see #getComponents
     */
    private java.util.List<Component> component = new java.util.ArrayList<Component>();
    

    Components are added by the protected void addImpl(...) method, which is invoked from the public Component add(Component comp) method in Container.

    So it's all private. You're not supposed to see that. ;-)