Results 1 to 10 of 10
  1. #1
    jshailes is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default Basic MouseListener Question

    Hi, I have a really basic question that I can't find the answer to online. Would anyone mind explaining where my understanding is lacking.

    Below is some pseudo code explaining an example of implementing a mouse listener that doesn't work:
    Java Code:
    class MainApplet extends JApplet
      init() {  
        add(new MyJComponent())
      }
    
    
    class MyJComponent extends JComponent implements MouseListener
      public void mouseClicked(MouseEvent e) {
        System.out.println("hello")
      }
      public void paint(g)
        ...

    Since a component in the applet has a mouse listener I would expect the component to know to watch for mouse events automatically, however it seems that I need to do this:


    Java Code:
    class MainApplet extends JApplet implements MouseListener
      init() {  
        MyJComponent c = new MyJComponent()
        c.addMouseListener(this)
        add(c)
      }
      public void mouseClicked(MouseEvent e) {
        System.out.println("hello")
      }
    
    class MyJComponent extends JComponent
      public void paint(g)
        ...
    placing the handling of all mouse events in the hands of the applet. I'm sure I must be doing something wrong.

    Many Thanks,

    James

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Just creating a MouseListener is not enough. You also need to add that mouselistener to the component via addMouseListener. Myself, I would avoid having either the MainApplet or the MyJComponent classes implement MouseListener and instead would use an inner class -- if it is a real small listener than an anonymous inner class, if bigger than a non-anonymous inner class, or if bigger still than the mouse listener could be in its own stand alone class.

    For instance an example of both a private inner and an anonymous inner class:
    Java Code:
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JComponent;
    
    public class MyJComponent extends JComponent
    {
      public MyJComponent()
      {
        addMouseListener(new MyMouseListener()); // add inner private class
        
        addMouseListener(new MouseAdapter() // add anon inner class
        {
          public void mousePressed(MouseEvent e)
          {
            String point = "[" + e.getPoint().x + ", " + e.getPoint().y + "]";
            System.out.println("From Anon Inner Class, Press at: " + point);
          }      
        });
      }
      
      // inner private class
      private class MyMouseListener extends MouseAdapter
      {
        public void mousePressed(MouseEvent e)
        {
          String point = "[" + e.getPoint().x + ", " + e.getPoint().y + "]";
          System.out.println("From Inner Private Class, Press at: " + point);
        }
      }
      
    }
    Last edited by Fubarable; 01-14-2009 at 02:32 PM.

  3. #3
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    I see that addMouseListener().

    I believe the problem lies with your component. Just extending JComponent doesn't do much in terms of taking up space on the display. Your component will only receive mouse events when the mouse is over it. Try changing you component to a JPanel and setting preferredSize and a backgroundColor. This will make it take up space, and you will be able to see where it is. JLabel would work well, also.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Abuse reported on stuv602

  5. #5
    jshailes is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default

    Thanks for your reply. I have tried an example and it appeared to work until I tried using it in the current application! I think I've nailed down where my problem is and its that Jcomponents can't have objects in them that have listeners?

    Java Code:
    public class MyComponent extends JComponent {
    	public MyComponent() {
    		JButton btn = new JButton();
    		btn.addMouseListener(new MouseAdapter() // add anon inner class
    	    {
    	      public void mousePressed(MouseEvent e)
    	      {
    	        String point = "[" + e.getPoint().x + ", " + e.getPoint().y + "]";
    	        System.out.println("From Anon Inner Class, Press at: " + point);
    	      }      
    	    });
    		add(btn);
    	}
    }
    If I add this component to an applet then the button does not appear, unless I implement the paint method. If I implement the paint method then the action listener still doesn't work. Does that make sense?

  6. #6
    jshailes is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default

    hi. thanks for your reply about the jpanel. I did try this with the example above and it did resolve the problem. However my JComponent is simply going to be a Line2D instance and therefore wrapping it in a panel leave a huge border around the outside of each line. Is it possible to make the JPanel exactly the same dimensions as the line (e.g. 2 pixels wide)?

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    that Jcomponents can't have objects in them that have listeners
    This is not true. Your problem must be somewhere else. But on a separate note, why would you add a mouse listener to a button and not an action listener?

    edit: likely you haven't set the layout of your JComponent yet. try setting it to flow layout

    sample code:

    Java Code:
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.JButton;
    import javax.swing.JComponent;
    
    public class MyJComponent extends JComponent
    {
      public MyJComponent()
      {
        setLayout(new FlowLayout());
        JButton button = new JButton("My Button");
        add(button);
        button.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
            System.out.println("button pressed");
          }
        });
        
        addMouseListener(new MouseAdapter() // add anon inner class
        {
          public void mousePressed(MouseEvent e)
          {
            String point = "[" + e.getPoint().x + ", " + e.getPoint().y + "]";
            System.out.println("From Anon Inner Private Class, Press at: " + point);
          }      
        });
      }
    }

    Java Code:
    import java.awt.Dimension;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    
    public class MyJComponentTest
    {
      private JPanel mainPanel = new JPanel();
    
      public MyJComponentTest()
      {
        MyJComponent jComp = new MyJComponent();
        jComp.setPreferredSize(new Dimension(300, 300));
        mainPanel.add(jComp);
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
    
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("MyJComponentTest");
        frame.getContentPane().add(new MyJComponentTest().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }
    Last edited by Fubarable; 01-14-2009 at 10:06 PM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by jshailes View Post
    hi. thanks for your reply about the jpanel. I did try this with the example above and it did resolve the problem. However my JComponent is simply going to be a Line2D instance and therefore wrapping it in a panel leave a huge border around the outside of each line. Is it possible to make the JPanel exactly the same dimensions as the line (e.g. 2 pixels wide)?
    You can set the preferred size of the jpanel or jcomponent to whatever size you'd like, though this seems a bit funny here. What are you trying to achieve with a very skinny jpanel here? Perhaps there's a better way to solve this then to force some kluge.

  9. #9
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Not all components can hold other components. Rather than using something very basic like JComponent, choose something a little more advanced. I suggested JPanel just because you wanted to use a mouse listener. For something like a JButton, you would use an action listener. For a simple demo app, all you really need is a JFrame as a container and one component to display in it and to generate events.

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default

    > Not all components can hold other components.
    If we're talking about Swing components here, all Swing components inherit from JComponent, which subclasses Container and all inherit the add(...) method.

    Granted that all AWT components can't hold other components.

    Never even looked at SWT/GWT so I can't comment on those.

    db

Similar Threads

  1. Basic array question
    By jigglywiggly in forum New To Java
    Replies: 12
    Last Post: 01-09-2009, 05:44 PM
  2. Basic Question from Networking Beginner
    By JDCAce in forum Networking
    Replies: 7
    Last Post: 10-10-2008, 09:29 PM
  3. Basic question about EJB
    By javaplus in forum Enterprise JavaBeans (EJB)
    Replies: 2
    Last Post: 07-15-2008, 06:44 PM
  4. Very basic question
    By gvi in forum New To Java
    Replies: 2
    Last Post: 10-30-2007, 07:30 PM
  5. basic question about files
    By oregon in forum New To Java
    Replies: 1
    Last Post: 08-05-2007, 03:34 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •