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

查看:85
本文介绍了扩展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和Stack 溢出。

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);
        ................
    }

AND

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()查看我的意思的方法!)。

  • 如果使用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天全站免登陆