Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problems with static referencing non-static methods

Status
Not open for further replies.

markwaldin

Technical User
Jan 25, 2002
6
US
I am trying to add a keylistener to my program but run into problems referencing non-static methods from main. Here is the jist of it:

class myprogram {

respondToKey instanceofKeyresponse = new respondToKey();

class respondToKey extends keyAdapter {
dosomething;
}
public void main(){
myprograminstance = new myprogram();
myprograminstance.addKeyListener(instanceofKeyresponse);
}
}

This causes an error for referencing a non-static variable from a static context (main) which I would expect. But how go I go about getting the keylistener activated?

Any help would be appreciated.
 
Hi markwaldin,
It would be better for the adding of the KeyListener to be in the constructor of the class
Code:
myprogram
, which really should be called
Code:
MyProgram
.
In general, the
Code:
main (String [] args)
method is used to just get the program running, but not for specific initialization like adding listeners to objects. Since it is specific to the object itself, it should be done in the objects constructor.
Something like this:
Code:
public class MyProgram extends Component {
  
  private RespondToKey keyListener = new RespondToKey ();

  public MyProgram () {
    addKeyListener (keyListener);
  }

  public void main (String [] args) {
    MyProgram program = new MyProgram ();
  }

  class RespondToKey extends KeyAdapter {
    //Place Key Event code in here
  }
}
Hope this Helps,
MarsChelios
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top