jerome
jerome

Reputation: 11

differentiating dragging and selecting in Java's JTextArea

My Java application has several JTextAreas that the user can move around. I achieve this by adding a mouse motion drag listener to it.

  public void mouseDragged(MouseEvent e) {
    int deltaX = e.getXOnScreen() - screenX;
    int deltaY = e.getYOnScreen() - screenY;

    setLocation(myX + deltaX, myY + deltaY);
  }

I am having a problem differentiating when the user wants to select text within the JTextArea and when they want to drag it around. Any ideas?

Upvotes: 1

Views: 250

Answers (3)

dacwe
dacwe

Reputation: 43504

I would use a modifier, for example control e.isControlDown(), or another mouse button to drag the component.

Upvotes: 2

StanislavL
StanislavL

Reputation: 57421

Use viewToModel() to obtain caret position of pressed point. Check whether the caret position is between getSelectionStart() and getSelectionEnd(). If it's in selected region start drag.

Upvotes: 1

Rocky Pulley
Rocky Pulley

Reputation: 23311

You may want to handle the first mouse down, check to see if text is selected. If the mouse pointer is on the text then set it to a state to identify it as a drag.

Upvotes: 1

Related Questions