Santa Zhang
Santa Zhang

Reputation: 894

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:

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?

Upvotes: 1

Views: 1826

Answers (1)

StanislavL
StanislavL

Reputation: 57381

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

Upvotes: 3

Related Questions