none static Jbutton and context errors

DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: none static Jbutton and context errors

  1. #1
    Join Date
    May 2005

    none static Jbutton and context errors

    Is there a way of adding a actionlistener to a none static Jbutton within , "public static void main(String[] args)" without getting a error like this one.

    non-static variable this cannot be referenced from a static context

  2. #2
    Join Date
    Aug 2005
    No. it is not possible. The reason why is because a static method can never access a non-static variable.

    The code for adding the listener shouldn't be in the main. It should be with the constructor for the class.

    A static method "belongs" to the class. He has no relation with any object of the class.
    The JButton is not static. He doesn't "belong" to the class. He belongs to an object of the class. There is a different copy of him FOR EACH object of that class.
    From the main method, you can't refer to the JButton because there can be millions of JButtons(one for each object of the class). This is why static can't access non-static. It's like being in Times Square and screaming out "Hey John!".

    For more help,

  3. #3
    Join Date
    Nov 2004

    Well ....

    ...from within a static method you can create object instances and
    access the public methods and variables of those instances. E.g. if
    I have a JFrame, MyFrame, with a public JButton like

    public JButton btn=new JButton("Start");

    So, in the static void main (or any other static section):
    public static void main(String [] args) {
      MyActionListener act=new MyActionListener ();
      MyFrame f=new MyFrame();
      f.btn.addActionListener(act); // <-- accessing non static JButton
    The variables used inside a static method must either be declared as static
    outside the method, or declared within the method.
    eschew obfuscation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center