0

I posted a similar question a year ago, but it was not really well written and I didn't get an answer I could work with. Now I stand in front of the same problem. I got a JPanel (my content pane), where a MouseListener is implemented.

Everywhere I click, I get the exact coordinates of my mouse click. Except my JTextField components. When I click on those, the MouseEvent isn't even triggered. H

ow do I do this, so my mouse clicks on those will also call the mouse event?

Tried: setEnable(false) and setHighlighter(null)

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • A JTextField has a MouseListener added to it, so you can position the caret or select the text, therefore all MouseEvents are handled by the text field, not the panel. This will be true for other components like JButton, JTable, JList etc. `I posted a similar question a year ago, but it was not really well written` - this is no much better. You still haven't answered the "What is the X/Y problem". - why do you think you need to need to know when someone clicks on a JTextField? – camickr Mar 14 '19 at 17:34
  • Sorry thought I fixed the X/Y problem. I use the JTextField just to show some text. Like a JLabel showing a picture. There is no intend of the user interacting with it. I want to open a menu, when the user clicks on the JTextField. – Ragnaroek511 Mar 14 '19 at 17:40

1 Answers1

0

Sorry thought I fixed the X/Y problem.

The X/Y problem simply means you are telling us what your attempted solution is without telling us what your requirement is. We can't suggest a different approach if we don't know what you are trying to do.

I want to open a menu,

Now we know what the requirement is.

The solution is to add the MouseListener to the text field, not the panel. If you have the same popup of the panel and the text field, then you still need to add the listener to both the panel and the text field.

You can do this in one of two ways:

  1. Read the section from the Swing tutorial on Bringing up a Popup Menu for a working example.

  2. Note the above tutorial is a little old, you can also check out the setComonentPopuMenu(...) method of the JComponent class. This approach will create the listener for you.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Sorry I'm new to stack. Thank you very much for the help. Thought I might get around adding another MouseListener. <3 – Ragnaroek511 Mar 14 '19 at 17:59