Search code examples
javaswingjcheckbox

JCheckBox prevent changing checked status when click on text


JCheckBox it is inherited from JToggleButton, so clicking on text will have same effect of clicking the checkbox. But now I need a JCheckBox which behaves like this:

  • Clicking on checkbox: check or uncheck the checkbox;
  • Clicking on text: don't update the checkbox, but emit an ActionEvent.

Currently I am using a ugly hack by overriding the processMouseEvent() function in JCheckBox, and only propagating it to super if the mouse is clicking on left part of the CheckBox. The code is like this:

public class MyCheckBox extends JCheckBox {

    @Override
    protected void processMouseEvent(MouseEvent e) {
        if (e.getX() < this.getHeight()) {
            super.processMouseEvent(e);
        } else {
            this.fireActionPerformed(new ActionEvent(this, 0, "click on text"))
        }
    }
}

Is there a more straightforward solution?


Solution

  • Add a JCheckBox without text and a separate JLabel for text with own listener.