简体   繁体   English

扩展JFrame的Frame类中提供的方法不能在main()中调用

[英]Methods present in Frame class, which extends JFrame, can't be invoked in main()

The code given below gives error ( Cannot make a static reference to the non-static method setVisible(boolean) from the type Window ) : 下面给出的代码给出错误( Cannot make a static reference to the non-static method setVisible(boolean) from the type Window ):

import javax.swing.JFrame;

public class Frame extends JFrame{
    public static void main(String[] args) {
        setVisible(true);
    }
}

While this one compiles fine : 虽然这个可以编译:

import javax.swing.JFrame;

public class Frame extends JFrame{
    Frame() {
        setVisible(true);
    }
}

When I say Frame extends JFrame , this means that Frame inherits all the methods from JFrame (loosely saying), including setVisible(boolean) . 当我说Frame extends JFrame ,这意味着Frame继承了JFrame的所有方法(松散地说),包括setVisible(boolean) So why can't I invoke setVisible(true) in main() , while I can do so in other methods? 那么,为什么不能在main()调用setVisible(true) main() ,而又可以在其他方法中调用呢?

The clue is in the exception message. 线索在异常消息中。

The setVisible method is an instance method on JFrame setVisible方法是JFrame上的实例方法

in public static void main , you are in a static context, so there is no instance of Frame to call setVisible on. public static void main ,您处于静态上下文中,因此没有Frame实例可以调用setVisible

You could do: 您可以这样做:

public static void main(String[] args) {
    new Frame().setVisible(true);
}

because then you have an instance 因为那时你有一个实例

https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html might help https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html可能有帮助

The problem is that you are trying to call a method from main() which is as you can see static. 问题是您试图从main()调用方法,就像您看到的一样。 However the setVisible() method is not static. 但是, setVisible()方法不是静态的。

The error you are getting is exactly explaining that. 您得到的错误正好解释了这一点。 In a static context you can only call static method. 在静态上下文中,您只能调用静态方法。 setVisible() is not static therefore you need to have an instance of your Frame class in order to call the method. setVisible()不是静态的,因此您需要具有Frame类的实例才能调用该方法。 Could be in your main: 可能在您的主目录中:

Frame myFrame = new Frame()
myFrame.setVisible(true)

Disclaimer: sorry for any mistake you may see on this answer I am on the phone. 免责声明:对于您在此电话上看到的任何错误,我们深感抱歉。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM