扩展 JFrame 与在程序中创建它 [英] Extends JFrame vs. creating it inside the program

查看:13
本文介绍了扩展 JFrame 与在程序中创建它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Swing 制作应用程序时,我看到人们通过以下两种方式之一来创建 JFrame.哪种方法更好,为什么?

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?

我是 Java 和编程的初学者.我唯一的学习来源是书籍、YouTube 和 StackOverflow.

I'm a beginner at Java and programming. My only source of learning is books, YouTube and Stack Overflow.

import {imports};

public class GuiApp1 {

    public static void main(String[] args) {

        new GuiApp1();
    }

    public GuiApp1()  {
        JFrame guiFrame = new JFrame();

        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiFrame.setTitle("Example GUI");
        guiFrame.setSize(300,250);
        ................
    }

import {imports};

public class GuiApp1 extends JFrame {

    public Execute() {
        getContentPane().setBackground(Color.WHITE);
        getContentPane().setLayout(null);
        setSize(800, 600);
        .............
    }

    public static void main(String[] args) {
        Execute frame1 = new Execute();
        frame1.setVisible(true);

    }
}

推荐答案

思考:

  • 避免扩展 JFrame,因为它会将您的 GUI 与 JFrame 联系起来.相反,如果您专注于创建 JPanel,那么您可以在任何需要的地方自由使用这些 JPanel——在 JFrame、JDialog、JApplet 或另一个 JPanel 内部,或通过 CardLayout 与其他 JPanel 交换.
  • 一般避免继承,尤其是复杂的类.这将防止有害错误,例如无意的方法覆盖(尝试创建具有 getX()getY() 方法的 JFrame 或 JPanel 以了解我的意思!).
  • 如果您使用的是 IDE,请避免继承复杂的类:如果您覆盖一个复杂的类,那么当您对这些类的对象调用方法时,您将有很多方法可供选择.
  • 封装很好,并且允许创建更安全的代码.仅公开需要公开的内容,并尽可能控制该公开.
  • 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.

这篇关于扩展 JFrame 与在程序中创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆