Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

save on close problem?

 
Berdy Ahern
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I wish to save a file on close but it wont allow me to refrence any objects as it is static where I'm trying to set it up. My main class "TabDemo" has implenents actionListener but I can't also put implements WindowListener can I?
Please can you tell me how I might get this WIndowListener to work?
Here is a bit of the code:

The errors it gives me are like this:
C:\TabDemo.java:326: non-static variable this cannot be referenced from a static context
frame.addWindowListener(this);
^
C:\TabDemo.java:326: addWindowListener(java.awt.event.WindowListener) in java.awt.Window cannot be applied to (TabDemo)
frame.addWindowListener(this);
^
2 errors
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you're running inside a static method (such as main), there is no such thing as "this" as the method belongs to the class itself and not to a particular instance of the class.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Berdy Ahern:
My main class "TabDemo" has implenents actionListener but I can't also put implements WindowListener can I?

Yes actually you can. A class can implement multiple interfaces but can only extend one class.

As James mentions above, you cannot use the keyword "this" in a static method since there is no "current object". If I understand what you are doing, you should change

to

This will also mean that TabDemo needs to implement WindowListener which, as I said before, is not a problem even if it already implements ActionListener or any other interface.

HTH

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic