1

I've created a component that basically is a JPanel fully covered with (non-editable) JTextAreas. I want a MouseListener to be fired everytime the JPanel area is being clicked on. I do want to add the Listener once to the JPanel instead of n times to the JTextAreas.

Is there a way to send the JTextAreas to background, so the JPanel is clicked "through" the JTextArea?

Note: With JLabels this works without anything special, the JPanels Listener is always fired, but I prefer JTextAreas, because of the linebreak.

Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
user4591830
  • 35
  • 1
  • 7

2 Answers2

0

There is a solution proposed here, but it might not fully work for your needs.

I don't know if there is a way around adding the listener n times, but if there is not, you could integrate the process cleanly in your code.

For example, with a dedicated method to add the JTextAreas:

public void addJTextArea(JTextArea tArea){
    this.add(tArea, ...);
    tArea.addMouseListener(this.listener);
}

Or even more transparently with an extended JTextArea:

public class ClickableTextArea extends JTextArea {
    public ClickableTextArea(MouseListener listener){
       super();
       addMouseListener(listener);
    }
}
Community
  • 1
  • 1
Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
  • Thank you for your answer too! I would have preferred another solution, as my program will be quite performance intensive, but as there is none, I'll do it that way. – user4591830 Jul 07 '15 at 15:29
0

With JLabels this works without anything special, the JPanels Listener is always fired

This is because by default a JLabel does not contain a MouseListener so the MouseEvent is passed up the parent tree until a component the does use a MouseListener is found.

In the case of a JTextArea a MouseListener is added to the text area so you can position the caret and select text etc. If you don't need all this functionality you can remove the MouseListener from each text area with code something like:

JTextArea textArea = new JTextArea(...);

MouseListener[] ml = (MouseListener[])textArea.getListeners(MouseListener.class);

for (int i = 0; i < ml.length; i++)
    textArea.removeMouseListener( ml[i] );

However, since you have to do that for every text area, I would suggest it is easier to just add the MouseListener to each text area. You can share the same MouseListener with every text area.

camickr
  • 321,443
  • 19
  • 166
  • 288