Extends JFrame vs. creating it inside the program

后端 未结 6 614
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:10

    Personally, the first approach (creating an instance of JFrame) is preferred, I prefer this because...

    It doesn't lock your application into a dedicated container...you see a lot of people wanting to add applets to frames and frames to applets, if they had simple put the majority of there GUI in a JPanel to start with, they wouldn't have these issues.

    It also means that the UI you create is much more flexible. For example, you can re-use it, either in the current application or future applications, you don't lock yourself in.

    The main gripe I have with extending JFrame is, you're not actually adding any new features or functionality to it, which could be effectively re-used beyond using setVisible

    The other issue I have with extending JFrame is people then promptly override paint, which is really, really bad. There are so many issues with doing this it's simply painful to have to repeatedly list them...

    So...for more 2 cents worth. Create an instance of JFrame and add your content to it. If required, create a static method call showMyAwesomeGUI which does it for you...

提交回复
热议问题