Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't you extend JFrame and other components? [duplicate]

I've seen this come up here a few times, but in the postings I've seen, no one explained it. Why shouldn't I extend JFrame (or any component)? Are there conditions where I should extend a component, or is this a firm rule that you don't?

like image 490
Thomas Owens Avatar asked Jul 17 '09 15:07

Thomas Owens


People also ask

Should you extend JFrame?

Thoughts: Avoid extending JFrame as it ties your GUI to being, well a JFrame. If instead you concentrate on creating JPanels instead, then you have the freedom to use these JPanels anywhere needed -- in a JFrame, or JDialog, or JApplet, or inside of another JPanel, or swapped with other JPanels via a CardLayout.

Does JPanel extend JFrame?

You can't do it. Jpanel and jframe are both classes and java doesn't support multiple inheritance of classes.

What is JFrame used for?

JFrame is a top-level container that provides a window on the screen. A frame is actually a base window on which other components rely, namely the menu bar, panels, labels, text fields, buttons, etc. Almost every other Swing application starts with the JFrame window.


2 Answers

Generally speaking, extending the component tends to be done strictly to use the component. This severely limits your options in unnecessary ways in terms of design, so that your classes can't extend different classes, you can't hide the JFrame's methods causing it to be more difficult to maintain and easier to trigger unexpected bugs when using the class.

Typically the intention is strictly to use the class to draw a frame, and composition is preferred over inheritance.

That being said, subclassing should be fine when you intend your subclass to add project-specific functionality to the Frame (such as convenience methods and the like) where the subclass would be used instead of the Frame itself, but used as a frame in general, not as a view of a specific frame in the application.

like image 165
Yishai Avatar answered Oct 09 '22 02:10

Yishai


Prefer composition over inheritance. All the usual reasons. Composition forces less dependencies between code.

Swing, and event AWT, components are hideously complicated. You don't want to be getting into that mess. You can easily override methods accidentally. In cases where you do need to override methods, it's difficult to see where that is done if it is amongst normal code.

like image 39
Tom Hawtin - tackline Avatar answered Oct 09 '22 02:10

Tom Hawtin - tackline