Reputation: 21
I am researching about AWT as Frame
, JFrame
and I saw object Contianer
as parent of them but I wonder that can I use container object as Frame
or JFrame
, below is my code but it's not working:
public class icontainer {
public static void main(String[] args) {
Container icon= new Container(); // new JFRAME();
icon.setSize(300,300);
icon.setLocation(300, 300);
icon.setVisible(true);
}
}
Why don't we use icon = new Container()
instead JFrame
?
Upvotes: 0
Views: 379
Reputation: 7795
That is not how inheritance works.
A Container is a base class that does not much more but keeping track of its children. And that is it. Its not a window itself.
From the Javadoc:
A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components.
Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).
But that is it. There is no mention of a window anywhere. It doesn't display anything on its own. It is displayed in something else.
A JFFrame on the other hand is a window (it literally inherits from java.awt.Window via java.awt.Frame).
From the Javadoc of java.awt.Frame:
A Frame is a top-level window with a title and a border.
And then there are some details about how the Frame layouts the contents etc.pp, and how the window decorations should look like and behave, especially wrt. WindowEvents like WINDOW_CLOSING. Those are things that are all only present in Frames, not Containers.
And if you go down to JFrame, you get some specialized handling of e.g. the content pane to make it work better with the JFC/Swing component architecture.
Container window = new Container();
This is code you can write, but nearly useless. In order for the container to actually be displayed on screen, it still needs to be put into a window.
Container window = new JFrame();
You can do that, because JFrame is a subclass of container, and thus is assignment-compatible to Container. However, you lose the ability to call any methods introduced by java.awt.Window, java.awt.Frame or javax.swing.JFrame on the container -- because those don't exist on Container.
Upvotes: 1
Reputation: 135
You should use a JFrame or Frame, because a Container of its own is not a "Window" that is displayed to the User.
I do not recommend it, but you could store your JFrame or Frame as a Container like this:
Container icon = new JFrame();
icon.setSize(300,300);
icon.setLocation(300, 300);
icon.setVisible(true);
Upvotes: 0