简体   繁体   中英

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 ) :

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) . So why can't I invoke setVisible(true) in main() , while I can do so in other methods?

The clue is in the exception message.

The setVisible method is an instance method on JFrame

in public static void main , you are in a static context, so there is no instance of Frame to call setVisible on.

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

The problem is that you are trying to call a method from main() which is as you can see static. However the setVisible() method is not static.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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