1

Anyone know why the error "Cannot make a static reference to the non-static method FileMenu() from the type Menu" appears?

import javax.swing.JOptionPane;

public class Menu {

    public void FileMenu() {            
    }

    public void ViewMenu() {
    }

    public static void main(String[] args) {
        String[] mainbuttons = { "File", "View" };

        int choice = JOptionPane.showOptionDialog(null, "Please Select An Option: ","Application Menu",JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,mainbuttons, mainbuttons[2]);

        switch (choice) {
            case 0:
                FileMenu();
                break;
            case 1:
                ViewMenu();
                break;
        }
    }       
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
user2964762
  • 93
  • 2
  • 11
  • 1
    It happens because you are accessing the non-static `FileMenu` from the static `public static void main(String[] args){`. If you change `FileMenu` and `ViewMenu` to static (`public static void ...`), it will work. – Justin Nov 08 '13 at 23:24
  • You need to make FileMenu() and ViewMenu() static functions since they are part of the same class as Main(). A static function can only call other static functions. – Andrew - OpenGeoCode Nov 08 '13 at 23:26

2 Answers2

0

Isn't it obvious FileMenu() in your code is not a static method and down in switch statement you are calling it in static context(i.e. without an object).You have two options here

  1. Make FileMenu() method static like public static void FileMenu() and then you can call it without any object of Menu class.

  2. Create an object of Menu class and use it to call FileMenu() method. like

    Menu obj = new Menu();

    obj.FileMenu();

Prateek
  • 1,916
  • 1
  • 12
  • 22
0

That means you cant call the non static method inside the static method (your case static void main(String[] args)).

to work properly make methods FileMenu() and ViewMenu() to static

public static void FileMenu() {

}

public static void ViewMenu() {


}

or

create Menu object and call the FileMenu() and ViewMenu() methods .

Menu m = new Menu();

switch (choice) {
    case 0:
        m.FileMenu();
        break;

    case 1:
        m.ViewMenu();
        break;

    }
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64