Search code examples
javaswingjcheckbox

Is there a way to customise Java's setEnabled(false)?


Let's say you have a JCheckBox you want to use as an on/off indicator. You use setEnabled(false) to disable mouse clicks on the JCheckBox. But setEnabled(false) also grays out the checkBox and the checkBox's text. Is there a way to customise setEnabled(false) so that the graying out does not happen?

If that's not possible, is the only solution something along the lines of customising a ButtonModel?


Solution

  • You can subclass JCheckBox and override processMouseEvent/processKeyEvent to not do anything.

    public class ReadOnlyCheckBox extends JCheckBox {
        public ReadOnlyCheckBox (String text, boolean selected) {
            super(text,selected);
        }
    
        protected void processKeyEvent(KeyEvent e) {
        }
    
        protected void processMouseEvent(MouseEvent e) {
    
        }
    }