【问题标题】:Why do we have to import and then extend a JFrame, why cant we use it by just importing it? [closed]为什么我们必须导入然后扩展一个 JFrame,为什么我们不能只通过导入来使用它? [关闭]
【发布时间】:2014-09-05 11:39:07
【问题描述】:

在下面的代码中,JFrame是先导入后扩展的。已经导入后扩展它的原因是什么?为什么我们不能直接在导入时使用它,比如 Scanner ?

    import java.awt.FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;

    public class tuna extends JFrame{

        private JButton reg;
        private JButton custom;

        public tuna(){
            super("The Title");
            setLayout(new FlowLayout());            

            reg = new JButton("reg Button");
            add(reg);

            Icon x = new ImageIcon(getClass().getResource("xxx.png"));
            Icon y = new ImageIcon(getClass().getResource("yyy.png"));

            custom = new JButton("custom button" , x);
            custom.setRolloverIcon(y);
            add(custom);

            handler thehandler = new handler();
            reg.addActionListener(thehandler);
            custom.addActionListener(thehandler);
        }

        public class handler implements ActionListener{

            public void actionPerformed(ActionEvent event){

                JOptionPane.showMessageDialog(null, String.format("%s", event.getSource()));

            }
        }
}

提前致谢!

【问题讨论】:

  • 不要扩展JFrame,创建这个Object作为局部变量
  • 你不必扩展JFrame.你的问题是基于一个错误的前提。

标签: java swing inheritance import


【解决方案1】:

在这里,您基于 JFrame 对象定义金枪鱼类。您需要先导入 JFrame 类,否则 JVM 将不知道什么是 JFrame,从而无法创建 tuna 类。

您应该了解“导入”在 Java 中的含义。

顺便说一句,类的第一个字母应该总是大写字母。金枪鱼应该叫金枪鱼。

【讨论】:

  • 感谢您的提示和帮助!
【解决方案2】:

导入一个类,是为了让您可以使用该类,而无需在您正在编写的当前类中限定全名。

扩展一个类是创建一个新类,它是某个其他类的子类。这将使您的子类继承超类的属性和方法。

顺便说一句,您不需要扩展 JFrame。

【讨论】:

  • 当我试图找到它时,我读到了同样的东西。但是当我们导入它时会发生什么?我知道不是写 java.util.Scanner sc = new java.util.Scanner(System.in);,你可以简单地写 Scanner sc = new Scanner(System.in);我们只需要导入哪些函数??
  • 当你导入一个包或一个特定的类时,你可以实例化(如果可能的话)同一个类并访问它的公共方法
  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 2022-11-25
  • 2013-11-09
  • 2018-08-08
  • 2018-12-17
  • 2012-04-10
相关资源
最近更新 更多