Search code examples
javaswingdouble-clickcaretjtextcomponent

Disable double click selection in a JTextComponent


Generally when you double click in a text component, the entire word is selected.

I would like to disable selection of this single word but still maintain the ability to click and drag to select it.

Example: "The quick brown fox jumps over the lazy dog"

When I click and drag from the beginning of "The" to the end of "dog," the text is selected. However, when I double click "brown," "brown" is not selected and a different action can be preformed.

Does anyone know how I can achieve this?


Solution

  • Where edit is JTextComponent instance

    DefaultCaret c=new DefaultCaret() {
        public void mouseClicked(MouseEvent e) {
            int nclicks = SwingUtilities2.getAdjustedClickCount(getComponent(), e);
            if (! e.isConsumed() &&
                    SwingUtilities.isLeftMouseButton(e) &&
                    nclicks == 2
                    && SwingUtilities2.canEventAccessSystemClipboard(e)) {
                return;
            }
    
            super.mouseClicked(e);
        }
        public void mousePressed(MouseEvent e) {
            int nclicks = SwingUtilities2.getAdjustedClickCount(getComponent(), e);
            if (! e.isConsumed() &&
                    SwingUtilities.isLeftMouseButton(e) &&
                    nclicks == 2
                    && SwingUtilities2.canEventAccessSystemClipboard(e)) {
                return;
            }
            super.mousePressed(e);
        }
    };
    c.setBlinkRate(edit.getCaret().getBlinkRate());
    edit.setCaret(c);