0

So I have a Java Swing program and I want to be able detect mouse clicks.

addMouseListener(new java.awt.event.MouseAdapter() {
 public void mouseClicked(java.awt.event.MouseEvent evt) {
 update(evt); //another method in the program
 }
});

The code works if I click on the window's side or places where there isn't an object, but does not work when I click on objects in the JFrame, such as my JTable or my text field.

Please help me how to have the MouseListener work on objects inside the JFrame as well.

Andrew Thompson
169k42 gold badges224 silver badges441 bronze badges
asked Apr 27, 2014 at 1:24
6
  • What is the point of the MouseListener, what does it do? Commented Apr 27, 2014 at 1:42
  • MouseListener detects mouse events like mouse movement and mouse clicks. Commented Apr 27, 2014 at 1:43
  • 1
    @Brandon Nguyen, I'm new to New to GUI in java, but I would imagine the components in the JFrame, such as your textbox etc need to also have the same mouse listener calling the method update(evt). I can't imagine that not working, but I really don't know for sure as I don't have time to test. There may be an easier way that I am unaware of, so I hope you get a good answer. Commented Apr 27, 2014 at 1:57
  • @nixxbb Yeah, but that would be such a pain to add the Listener to every single object. Commented Apr 27, 2014 at 1:58
  • I know, I hope you get a good answer. If I have time to play with it later I will check back... Commented Apr 27, 2014 at 1:59

1 Answer 1

1

When you click on a textfield, the textfield gains focus. That means your frame loses ownership of focus, and since your listener is most likely added to your frame, your listener stops working right when frame isnt in focus. Add your listener to all compoments, or use Key Binding

answered Apr 27, 2014 at 3:28
Sign up to request clarification or add additional context in comments.

1 Comment

Oh so that explains why. Thanks. I'll have to add more listeners then.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.