0

My error is on line 23-24. non-static variable cannot be referenced from a static context

I know why I am getting the error but I don't know how to fix it in this case:

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.AWTEvent;
    import java.awt.MouseInfo;
    import java.awt.Toolkit;

    public class VideoGamerEvent implements ActionListener {
        VideoGamer gui;
        String theEvent;
        String theCoords;

        public VideoGamerEvent(VideoGamer in){
            gui = in;
        }


        public static class Listener implements AWTEventListener {
            public void eventDispatched(AWTEvent event) {
                System.out.print(MouseInfo.getPointerInfo().getLocation() + " | ");
                System.out.println(event);

//error here
                theEvent = event.toString();
                theCoords = MouseInfo.getPointerInfo().getLocation().toString();
//end error

            }
        }

        public void actionPerformed(ActionEvent e){
            if(theEvent.contains("FOCUS_LOST")){
                gui.coords.setText(theCoords);
            }    
        }
    }

I need to eventually get theCoords into a JTextField (gui.coords).

SinTek Solutions
  • 105
  • 1
  • 1
  • 11

2 Answers2

2

You could...

  • Provide getters in the Listener which return the values
  • Provide an Observer Pattern to the Listener which would then provide notificaiton to interested parties about changes to the state of the Listener, from which they could then inspect the values via the getters
  • Use a "model" style class which could be used to set/get the values from and which could implement the Observer Pattern as suggested above

As a side note, you would need a very specific reason for using AWTEventListener, when you could simply use a MouseListener or MouseMotionListener to achieve the same results

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Try changing the variables for static:

static String theEvent;
static String theCoords;

and then this error will disappear.

  • No, no, no, please don't suggest the use of static in this manner. The OP should either be passing the values to the instance of the class, provide getters and/or setters or use a third/model class. This kind of advice just causes bad practices and long term problems which will need to be corrected in the future, and I don't like telling people that the previous advice they got was bad or wrong, especially from a professional forum – MadProgrammer Feb 17 '16 at 06:54