Google Tag Manager

2015/12/28

Copy on select for JTextArea

Code

class CopyOnSelectListener extends MouseAdapter implements CaretListener {
  private boolean dragActive;
  private int dot;
  private int mark;
  @Override public final void caretUpdate(CaretEvent e) {
    if (!dragActive) {
      fire(e.getSource());
    }
  }
  @Override public final void mousePressed(MouseEvent e) {
    dragActive = true;
  }
  @Override public final void mouseReleased(MouseEvent e) {
    dragActive = false;
    fire(e.getSource());
  }
  private void fire(Object c) {
    if (c instanceof JTextComponent) {
      JTextComponent tc = (JTextComponent) c;
      Caret caret = tc.getCaret();
      int d = caret.getDot();
      int m = caret.getMark();
      if (d != m && (dot != d || mark != m)) {
        String str = tc.getSelectedText();
        if (Objects.nonNull(str)) {
          //StringSelection data = new StringSelection(str);
          //Toolkit tk = Toolkit.getDefaultToolkit();
          //tk.getSystemClipboard().setContents(data, data);
          tc.copy();
        }
      }
      dot = d;
      mark = m;
    }
  }
}

References

No comments:

Post a Comment