为什么我们必须导入然后扩展JFrame,为什么我们不能通过导入它来使用它?

时间:2014-07-15 10:09:31

标签: java swing inheritance import

在下面的代码中,首先导入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()));

            }
        }
}
提前谢谢!

2 个答案:

答案 0 :(得分:2)

在这里,您可以根据JFrame对象定义金枪鱼类。您需要首先导入JFrame类,否则JVM不知道什么是JFrame,因此无法创建金枪鱼类。

你应该看到' import'用Java表示。

顺便说一下,一堂课的第一个字母应该是大写字母。金枪鱼应该叫金枪鱼。

答案 1 :(得分:1)

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

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

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

相关问题