Search code examples
javaprogram-entry-pointmouselistener

Sending MouseListener data back to the game handler


So my Java program has a Main class that creates and initializes the Game object. The Game class contains the code that handles the procession of my program. My Game class initializes my Display class. My Display class initializes my DisplayPanel class. My DisplayPanel class implements MouseListener.

My problem is that I want to send the MouseListener data back to the Game object on demand. But I can't access my the game object properly from DisplayPanel because it is contained within the Main class and method.

I can't think of a proper way to work around this. I'm sure this issue and issues like this are fairly common and would appreciate to know what the common and proper way to handle this issue and ones like this is.

I will post code if you really think it's necessary but I feel like I've explained everything you really need to know and it would be a waste of my time.


Solution

  • As established in the comments:

    The easiest way of getting this to happen would be in the Game class, like so:

    public class Game {
        private MouseListener mouseListener = new MouseListener() {
            public void onClick(MouseEvent e) {
                // application logic here
            }
    
            public Game() {
                DisplayPanel dp = new DisplayPanel();
                dp.addMouseListener(mouseListener);
            }
        };
    }
    

    Then, you simply direct it to the DisplayPanel class through a series of method calls:

    public class DisplayPanel extends JPanel {
        public void addMouseListener(MouseListener mouseListener) {
            this.addMouseListener(mouseListener);
        }
    }
    

    (Note that in this case, since JPanel has an addMouseListener method, implementing your own is unnecessary.)