I am using the middle mouse button for an autoscroller in a Java Swing application. However, when I middle-click on a text component, on Linux it pastes the last selected text, which is unwanted. How can I disable this?
This behavior is implemented in javax.swing.text.DefaultCaret.mouseClicked
. It has no obvious off switch.
As a workaround, run this block once at application startup. It clears the "selection" clipboard upon middle-click.
if (Toolkit.getDefaultToolkit().getSystemSelection() != null) {
Toolkit.getDefaultToolkit().addAWTEventListener((AWTEvent e) -> {
try {
if (e.getID() == MouseEvent.MOUSE_CLICKED && ((MouseEvent)e).getButton() == MouseEvent.BUTTON2) {
Toolkit.getDefaultToolkit().getSystemSelection().setContents(new StringSelection(""), null);
}
} catch (Throwable t) {} // any error here not worth blocking application
}, AWTEvent.MOUSE_EVENT_MASK);
}