Extends JFrame vs. creating it inside the program

后端 未结 6 767
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 04:39

When making an application using Swing, I\'ve seen people do one of the two things to create a JFrame. Which is a better approach and why?

I\'m a beginner at Java an

6条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:14

    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.
    • Avoid inheritance in general, especially of complex classes. This will prevent pernicious errors, such as inadvertent method overrides (try creating a JFrame or JPanel that has a getX() and getY() method to see what I mean!).
    • Avoid inheritance of complex classes if you are using an IDE: If you override a complex class, when you call methods on objects of these classes, you will have many, too many, choices of methods offered to you.
    • Encapsulation is good, is and allows for creation of safer code. Expose only that which needs to be exposed, and control that exposure as much as possible.

提交回复
热议问题