Java:创建 GUI。导入或扩展 JFrame?
我自己做了一个 GUI,它扩展了 JFrame。我看到了高级程序员导入JFrame的程序代码。我可能知道导入和扩展之间的区别。但哪种实施方式有什么好处呢?
I did a GUI by my own which extends a JFrame. And I saw a program code from advanced programmer who imports the JFrame. I might know the difference between import and extend. But what advantage is given by which sort of implementation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为“导入”是指您的程序员朋友的类使用 JFrame,而您的类是 JFrame。我不认为扩展 JFrame 是“错误的”,但我的首选方法是创建和配置 JFrame 而不是扩展它。如果您确实需要访问某些受保护的方法,那么您可能会扩展它,但我确信,在大多数情况下,简单地创建和配置标准 JFrame 是正确的 - 我从未发现需要扩展它。
换句话说,通过继承 JFrame 而没有真正需要这样做,只会使系统变得复杂。在选择继承与任何其他类的聚合时,您也会遇到同样的争论。要找出正确的方法,您需要问问自己,您正在编写的类是否真的是一个JFrame,它是一个窗口小部件。我怀疑在大多数情况下,您正在编写一个需要 JFrame 的 Swing 应用程序,但它本身并不是 JFrame - 它是一个具有其他用途的 Swing 应用程序。
By "import" i presume you mean that your programmer friend's class uses a JFrame whereas your class is a JFrame. I don't think extending a JFrame is "wrong", but my preferred approach is to create and configure a JFrame rather than extending it. If there's really some protected method that you need access to then you might extend it but i'm sure that, in most cases, simply creating and configuring a standard JFrame is right - i have never found a need to extend it.
In other words, by inheriting JFrame with no real need to do that, you're just complicating your system. This is a same argument you would have when choosing inheritance versus aggregation with any other class. To find out what's right, you need to ask yourself if the class you're writing really is a JFrame which is a window widget. I suspect that in most cases you are writing a Swing application which needs a JFrame but which isn't one itself - it's a Swing application with some other purpose.