Search code examples
javaswingeventsjcheckbox

Java, JCheckbox - consume / prevent all events, but still enable


I've got an icon, with a checkbox next to it, contained in a panel. The panel has a hover effect, and I want to select the box when the panel is clicked.

I'd like to consume or prevent all events to the checkbox, only selecting it programatically. I'd like the box to appear "enabled" onscreen, while "behind the scenes" it's pretty much non-functional. (Selection would happen from a click in the panel.)

Further, when I mouse enter/exit the checkbox, I'd like nothing to happen. I've got a hover effect on the panel. Right now, I can enter the panel, but then when I enter the box, the panel exits, and looks un-hovered.

So, how can I prevent all mouse-related activities on this checkbox - enter, exit, click, etc. From previous research I recall the buzzwords "consume events", but I can't seem to drum up the appropriate searches to make this happen :)

============

EDIT

enter image description here

This panel (purple) has an icon (hamburger) and a checkbox (UI LAF). I want to hover the panel, not lose the hover when I enter the checkbox, and toggle the checkbox when the (parent) panel is clicked.


Solution

  • My final solution for this was to use an EmptyBorder on the left side of the checkbox, and BlackPanda's mouse listener solution:

    public class CheckboxPanel extends JPanel {
        private final JCheckBox checkBox = new JCheckBox();
        private final Image img;
    
        public CheckboxPanel (final Image img0) {
            super();
            this.img = img0;
    
            // Left padding of 20 allows mouseovers on image that trigger the box.
            checkBox.setBorder(new EmptyBorder(0, 20, 0, 0)); 
    
            add(checkBox);
    
            this.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(final MouseEvent me) {
                    checkBox.doClick();
                }
            });
        }
    
        public JCheckBox getCheckBox() {
            return this.checkBox;
        }
    
        @Override
        protected void paintComponent(final Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, null);
        }
    }