Mouse Listening/ Get point/ Better class structure


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 11 of 11

Thread: Mouse Listening/ Get point/ Better class structure

  1. #1
    Join Date
    Sep 2005
    Location
    TX
    Posts
    23

    Mouse Listening/ Get point/ Better class structure

    Hi, I'm Nescafe. This is my first time to the forums. I'm a sophomore in college and intending to go into CPSC in the near future. Nonetheless, my breadth of knowledge concerning Java is still limited thought it is the language I have had the most experience with.

    Below is some code I recently wrote. I am intending to write a simple GUI that will report when the mouse enters my JPanel component, exits the component and while within the component reports the points of the mouse pointer. I have been successful with the first two scenarios but can't get the mouse point of the mouse pointer. I extended the MouseAdapter class and I thought that the mouseMoved() method would be called when the mouse is within my component. However, this does not seem to be the case.

    Furthermore, on a side not, you will see that I commented out an anonymouse class I had with in my constructor. Is this a good idea? Is the anonymouse class a bad idea w/in the constructor as oppsed to creating the inner class that I have: MouseMotionListener. In other words, do you guys have any reccomendations on how to structure to code in a better way, i.e. better structure, etc? Sorry about the long post but thanks for the help!!

    HTML Code:
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    
    public class MouseMotion{
    	
    	private JPanel mousePanel;
    	private JFrame frame;
    	private JLabel mouseLabel;
    	
    	public MouseMotion(){
    		frame = new JFrame("Moust Motion Listener");
    		frame.setLayout(new BorderLayout());
    		frame.setSize(300,300);
    		frame.setLocation(200,250);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		
    		mouseLabel = new JLabel("Listening for mouse movement......");
    		//add border to mouseLabel
    		//mouseLabel.setBorder(BorderFactory.createTitledBorder("Is Mouse Moving?"));
    		
    		mousePanel = new JPanel();
    		mousePanel.setBackground(Color.gray);
    		//setPreferredSize-- not working correctly!!
    		mousePanel.setSize(new Dimension(
    									frame.getWidth(), frame.getHeight() * (1/3)));
    		//add mouse listener to panel
    		mousePanel.addMouseListener(new MouseMoveListener());
    /*		
    		mousePanel.addMouseListener(new MouseAdapter(){
    			
    			public void mouseEntered(MouseEvent evt){
    				//System.out.println("mouse entered component");
    				mouseLabel.setText("Mouse entered component");
    			}
    			
    			public void mouseExited(MouseEvent evt){
    				mouseLabel.setText("<html>Mouse has <font color = red>left </font>component</html>");
    			}
    		});
    */		
    		frame.getContentPane().add(mousePanel, BorderLayout.CENTER);
    		frame.getContentPane().add(mouseLabel, BorderLayout.SOUTH);
    		//add border to JLabel later
    		frame.setVisible(true);
    	}
    	
    //MouseAdapter class	
    	private class MouseMoveListener extends MouseAdapter{
    		public void mouseEntered(MouseEvent evt){
    			mouseLabel.setText("<html>Mouse has <font color = blue>entered</font> component</html>");
    		}
    		
    		public void mouseExited(MouseEvent evt){
    			mouseLabel.setText("<html>Mouse has <font color = red>exited</font> component</html>");
    		}
    		
    		public void mouseMoved(MouseEvent evt){
    			//System.out.println("mouseMoved event");
    		}
    	}
    	
    	public static void main(String[] args){
    		JFrame.setDefaultLookAndFeelDecorated(true);
    		new MouseMotion();
    	}
    }

  2. #2
    Join Date
    Jul 2005
    Location
    SW MO, USA
    Posts
    299
    A quick comment on using MouseAdaptor. It defines all the methods needed for the MouseListener interface. If you attempt to override one of the methods in the MouseListener interface but misspell it, there will be NO notice made. Your misspelled method will NOT be used and you can spend hours trying to figure out what is wrong.

    I'd recommend putting println() statements in ALL of the MouseListener methods to see when and if they are being called. I'd also have listener code for the enclosing Frame to see when its receiving calls.

  3. #3
    Join Date
    Sep 2005
    Location
    TX
    Posts
    23
    Well, I don't know what exactly you're implying about the spelling. I know everything is spelled correctly.

    However, I realized that I extended the MouseAdapter class but that there is no mouseMoved method in the class. So of course that's why the method wasn't getting called.

    On another note, I can understand your reasoning for adding a listener to the JFrame. I wouldn't really ever need to be concerned with the JFrame except in a few limited cases. That's how I feel about that at least.

  4. #4
    Join Date
    Jul 2005
    Location
    SW MO, USA
    Posts
    299
    Your mouseMoved() method in the MouseAdapter class is a perfect example of what I was trying to say. You thought thatyour method would be called but it was not a method for that type of listener so it was never going to be called. The compiler didn't give an error because all of the methods for the interface were in the Adapter class. If you had NOT used the adapter class, you have a better chance of the compiler helping you.
    You still can have the same problem if you add methods beyond those required by the interface definition. I think it is better to have your own template of methods to copy into your code and modify than to use an Adapter class.

  5. #5
    Join Date
    Sep 2005
    Location
    TX
    Posts
    23

    Lightbulb Gotcha

    Well I was using the Adapter class so that I wouldn't have to implement all the methods from the MouseListener interface. I failed to notice the lack of the mouseMoved method. Thanks though.

    By template do you mean write my own interface for mouse events?
    I wouldn't know how to go about that.

  6. #6
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    I agree w. Norm that is is better to do it by implementing the listener
    interface(s) and pasting in a block of code for that. I only use adapters
    when I'm in a hurry; I just double click the buttons and have my IDE insert
    that messy adapter code.

    Here is a fragment of the template idea, with an extra little timesaver method.

    Code:
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    
    
    
    public class MouseMotion implements MouseMotionListener, MouseListener {
    
      private JPanel mousePanel;
      private JFrame frame;
      private JLabel mouseLabel;
    
      public MouseMotion() {
        frame = new JFrame("Moust Motion Listener");
        frame.getContentPane().setLayout(new BorderLayout());
        frame.setSize(300, 300);
        frame.setLocation(200, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        mouseLabel = new JLabel("Listening for mouse movement......");
    
        mousePanel = new JPanel();
        mousePanel.setBackground(Color.gray);
    
        mousePanel.setSize(new Dimension(
            frame.getWidth(), frame.getHeight() * (1 / 3)));
    
        frame.getContentPane().add(mousePanel, BorderLayout.CENTER);
        frame.getContentPane().add(mouseLabel, BorderLayout.SOUTH);
    
        hookUpMouse(frame);
    
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        new MouseMotion();
      }
      /**
       * This method adds this class as a mouselistener to all components 
       * inside the passed container.  If container is a complex application
       * frame with subpanels, buttons, checkboxes etc. then this 
       * method will get them all.
       * @param c
       */
      private void hookUpMouse(Container c) {
        Component [] cc=c.getComponents();
        for (int i=0; i<cc.length; i++) {
          cc[i].addMouseListener(this);
          if (cc[i] instanceof Container) {
            cc[i].addMouseMotionListener(this);
            hookUpMouse((Container)cc[i]); // recursion to inner container
          }
        }
      }
      // ** Start of template code block
      // MouseMotionListener
      public void mouseDragged(MouseEvent e) {}
      public void mouseMoved(MouseEvent e) {
       System.out.println("mouseMoved: "+e.getPoint());
      }
      // MouseListener
      public void mouseClicked(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {
        mouseLabel.setText(
              "<html>Mouse has <font color = blue>entered</font> component</html>");
      }
      public void mouseExited(MouseEvent e) {
        mouseLabel.setText(
              "<html>Mouse has <font color = red>exited</font> component</html>");
      }
      // ** End of template code block
    }
    eschew obfuscation

  7. #7
    Join Date
    Jul 2005
    Location
    SW MO, USA
    Posts
    299
    That template is a bit more than I'd use. I was suggesting the bare minimum. Just code all the the methods needed in an interface as empty methods such as the following:
    public void mouseMoved(MouseEvent me) {}
    Do this for ALL the methods in an interface.

    To make sure the set of methods I've created is complete and correct, I change the method names (say by adding XXX at the end of the name) and compile the interface. The compiler will tell you which methods it wants. I then rename the ones referenced in the error messages by removing the XXX and compile the interface again. If there are no errors now, I know that any methods remaining that are still renamed with the XXX are NOT part of the interface and can be deleted.

  8. #8
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    That would include the parameters too I assume, I admit I don't use any templates, I
    just use the interface wizard for that.

    btw: For those two mouselisteners, thats the requirement, well, apart from the extra example code....
    Last edited by sjalle; 09-26-2005 at 10:00 AM.
    eschew obfuscation

  9. #9
    Join Date
    Jul 2005
    Location
    SW MO, USA
    Posts
    299
    I program in Java for a hobby and have 10 wizards to help me with my code.
    I tried using an IDE a while back and got frustrated with it and gave up. I use templates and/or cut and paste from other code.

  10. #10
    Join Date
    Sep 2005
    Location
    TX
    Posts
    23

    Red face

    I still don't quite get what y'all mean by 'template.'

    If that is a template than how does it differ from just implementing an interface(s) and then implementing the methods of the interface.
    I mean when you say 'implements GeneralInterface' you're just agreeing to implement all the methods contained w/in the interface, right?

    How does that differ from a 'template'?
    Perhaps, I'm getting confused over the wording.

    still, what sjalle did and what I'm describing above seem to be one in the same though he characterizes it as a template.

    This thread has gone on for a while; feel free not to respond.
    ??????????????

  11. #11
    Join Date
    Jul 2005
    Location
    SW MO, USA
    Posts
    299
    By a template I mean a skeleton piece of code that has the bare necessity of definitions in it to compile. For the listeners mentioned above it would consist of the empty methods needed for the interface. To use it, you would copy and paste it into your code and then add code to the various places that needed it.
    My one attempt at wizardry is to have written a program that will build a GUI for my applications. When I need a utility to do something, the code for it usually takes only half the time, the rest of the time is taken up by GUI programming. My last app was for converting HTML to text files. I had the methods to do that, but needed a GUI to where I could enter the filename(s) and display the results. etc etc

Similar Threads

  1. Replies: 1
    Last Post: 09-01-2002, 08:52 AM
  2. Equivalent of VB6's Public Not Creatable Class
    By Wai-Yin Chee in forum .NET
    Replies: 8
    Last Post: 09-27-2001, 05:04 PM
  3. How To Do It - Shared Class Variables Part III
    By Patrick Ireland in forum .NET
    Replies: 5
    Last Post: 05-10-2001, 06:19 PM
  4. How To Do It - Shared Class Variables Part IV
    By Patrick Ireland in forum .NET
    Replies: 3
    Last Post: 05-07-2001, 03:04 PM
  5. Replies: 0
    Last Post: 04-26-2001, 10:01 PM

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
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

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