Andrew Martin
Andrew Martin

Reputation: 5761

When using JFrame, where does the add() method come from?

I've been roaming the Internet looking for an answer to this question, but have come up rather empty handed.

I'm following a JFrame practical from university, and using my lecture notes and the advice on the practical guidance sheet I have this basic code:

public HelloFrameMenu()
{
    message = "Hello, World!";
    label = new JLabel(message);
    label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
    add(label, BorderLayout.CENTER);
    createSouthPanel();

    setSize(FRAME_WIDTH, FRAME_HEIGHT);
}

This creates a text message on my JPanel and executes the createSouthPanel() method which works fine and adds some menu lists to the JFrame.

My question is regarding the add function. I don't understand what this is part of. I thought if it was a static method, its class name would precede it. As it doesn't, I assumed it was part of the JFrame package or one of the classes automatically loaded by Java, but I can't find the method in either.

Where does this method come from?
Why is it not preceded by anything?
What other methods can be used like this?

Upvotes: 1

Views: 18044

Answers (5)

Reimeus
Reimeus

Reputation: 159844

JFrame#add is an instance method that is inherited from java.awt.Container. It is not preceded by any instance here as you have subclassed a JFrame directly. Normally you are not adding any new functionality to the frame so the preferred approach is to create an instance directly and use:

JFrame myFrame = new JFrame();
...
myFrame.add(...);

Check out the javadoc for all available methods.

Upvotes: 2

David Lavender
David Lavender

Reputation: 8331

It's to do with Inheritance. Java is an object oriented language which means that (almost) everything is an object.

Objects can then be arranged in a hierarchy.
eg a Cat object might extend an Animal object. It inherits all the behaviour (methods) of Animal, and can add its own.

In your case, JFrame extends Container and Container has an add method.

Upvotes: 1

amphibient
amphibient

Reputation: 31268

Class HelloFrameMenu would have to extend JFrame and the add method comes from Container and is used for adding visual components to the frame. It would be more intelligible if add and setSize were prefixed with super (e.g. super.add(...)), which is what I always to to denote that the method comes from a superclass.

Upvotes: 1

Srikant Krishna
Srikant Krishna

Reputation: 881

You can think of it as "this.add" as it is an inherited member from Container.

Upvotes: 1

assylias
assylias

Reputation: 328737

If you look at the javadoc, you will see that there is no add method in JFrame. However, several add methods are inherited from Container and Component, which are listed in the Methods inherited from... section.

Upvotes: 2

Related Questions