Java – should I inherit JFrame / JPanel?

I am used to subclassing window classes in other programming environments, but I often see similar things in Java tutorials @ H_ 502_ 2@JPanel p = new JPanel(); p.setLayout(new @R_316_ 2419@Layout (p,@R_316_ 2419@Layout.PAGE_AXIS )); p.add(aComponent); p.add(anotherComponent);

So what is the Convention in Java for subclassing top-level container classes?

Solution

Use the same principles as all Java classes If you want to modify or extend the behavior or function, you should extend JPanel or JFrame anyway The trick is to think carefully and make sure you're really adding anything In most cases, when I see people extending JFrame, this is unnecessary and wrong@ H_ 502_ 2@public class MyFrame extends JFrame { public static void main(String[] args) { new MyFrame().setVisible(true); } }

Why spend extending JFrame? You didn't add anything! Combination is a better choice

Extending JPanel is a little different JPanel is a rather abstract idea. It is just a general container for other components With all due respect, it is a subclass of JPanel, create a more specific panel, and then use it in your application It promotes OOP and encapsulation

For example, suppose your GUI has two main display areas; One with some buttons / controls / inputs and the other with display output (e.g. in the text area) It is entirely acceptable for a subclass JPanel to create a controlpanel containing buttons / controls / inputs This will move all the code into a nice neat module and clean up the classes that contain and process the main JFrame

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>