0

I get the error No enclosing instance of type mainframeclass is accessible when I try to compile/launch my program in Eclipse. Here is the code:

public class mainframeclass {

    public static Object mainframemenuitem1;

    public static void main(String[] args) {
        JFrame mainframe = new JFrame(variables.mainframename);

        mainframe.setLayout(new GridLayout());

        mainframe.setSize(variables.mainframewith, variables.mainframeheight);
        mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainframe.setVisible(variables.mainframevisible);
        mainframe.setResizable(variables.mainframeresizable);

        JMenuBar mainframemenubar = new JMenuBar();
        JMenu mainframemenu = new JMenu("File");
        JMenuItem mainframemenuitem1 = new JMenuItem("Exit");
        mainframe.setJMenuBar(mainframemenubar);

        mainframemenubar.add(mainframemenu);
        mainframemenu.add(mainframemenuitem1);

        actionlistener listen = new actionlistener();
        mainframemenuitem1.addActionListener(listen);

        runningclass.running();
    }

    public class actionlistener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == mainframemenuitem1)
                System.out.println("Test");
        }
    }
}

It seems that I have done something wrong with the:

actionlistener listen = new actionlistener();

but I don't know what. I am new to Java and would appreciate any insight into this problem. Thanks.

Perception
  • 79,279
  • 19
  • 185
  • 195

1 Answers1

4

Your actionlistener class (which should be renamed to follow Java naming conventions and with a more meaningful name) is an inner class (as opposed to a static nested class), which means it's only valid with an enclosing instance of mainframeclass to refer to... which it doesn't actually need, given that it refers to mainframemenuitem1 which is static anyway.

So you can just change it to:

public static class actionlistener implements ActionListener

and it should work. Well, it will compile, anyway. It won't actually do what you want because you've got two mainframemenuitem1 variables - the static one, and then a local one within your main method, so the static one never gets assigned a non-null value.

I would either pass mainframemenuitem1 into the constructor of actionlistener and still make it a static nested class, or just make mainframemenuitem1 final within the main method and create an anonymous inner class for the action listener.

Having said that:

i am kinda new to java

In that case, I would actually stop with GUIs entirely for the moment. It's much simpler to learn about a new language without the complications introduced by GUIs. Writing console applications allows you to concentrate on learning just one thing at a time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194