0

I have a problem while compiling a simple program. I started using Swing library two days ago, so i'm not good enough yet. The error is: "non-static variable this cannot be referenced from a static context", referred to "WindowsEraser listener = new WindowsEraser();". What is the problem?

public class prog9{
    public class WindowEraser extends WindowAdapter{
        public void windowClosing(WindowEvent e){
            System.exit(0);
        }
    }
    public static void main(String[] args){
        JFrame frame = new JFrame("Frame with buttons");
        frame.setSize(400,400);
        JLabel label = new JLabel("I'm a Window");
        frame.add(label);   
        WindowEraser listener = new WindowEraser();
        frame.addWindowListener(listener);
        frame.setVisible(true);
    }
}
Daesos
  • 99
  • 10

3 Answers3

0

make WindowEraser static otherwise main() can't access it

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

You can instantiate WindowEraser() in this way too:

WindowEraser listener = new prog9().new WindowEraser();
Francisco Hernandez
  • 2,378
  • 14
  • 18
-1

You can't refer to non static fields/classes/methods from static context (because static context can be initialized earlier and then there will be no reference to non-static entity)

You should make WindowEraser class static:

 public static class WindowEraser extends WindowAdapter
D. Rakov
  • 318
  • 3
  • 14