Articles Projects Tips Downloads Contacts About
 

Disabling word selection by double click in JTextComponent.

The requirement I met on forums and I think it could be useful. The selection is done by Caret so I just override DefaultCaret mouse events processing methods to skip the word selection code. The solution works for JEditorPane and JTextArea.

The source code of the example with disabled word selection by double click.

import sun.swing.SwingUtilities2;
 
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.event.MouseEvent;
 
public class DisableWordSelect extends JEditorPane {
 
    public static void main(String[] args) {
        JFrame frame = new JFrame("Disable word selection by double click example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final DisableWordSelect app = new DisableWordSelect();
        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(app.getCaret().getBlinkRate());
        app.setCaret(c);
        JScrollPane scroll = new JScrollPane(app);
        app.setText("Disable word selection by double click example");
        frame.getContentPane().add(scroll);
 
        frame.setSize(400, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}