001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.widgets;
003
004import org.openstreetmap.josm.tools.GBC;
005
006import javax.swing.Icon;
007import javax.swing.JCheckBox;
008import javax.swing.JLabel;
009import javax.swing.JPanel;
010import javax.swing.SwingConstants;
011import javax.swing.SwingUtilities;
012import java.awt.GridBagLayout;
013import java.awt.event.MouseAdapter;
014import java.awt.event.MouseEvent;
015
016/**
017 * Allows using an icon as well as a text on a {@link JCheckBox}
018 */
019public interface IconTextCheckBox {
020
021    /**
022     * Wraps the checkbox to display an icon as well as a text
023     * @param check the checkbox
024     * @param text the label text to display
025     * @param icon the icon to display
026     * @return a wrapping component
027     */
028    static JPanel wrap(JCheckBox check, String text, Icon icon) {
029        JPanel panel = new JPanel(new GridBagLayout());
030        JLabel label = new JLabel(text, icon, SwingConstants.LEADING);
031
032        panel.add(check, GBC.std());
033        panel.add(label);
034        panel.add(new JLabel(), GBC.eol().fill());
035
036        label.addMouseListener(new MouseAdapter() {
037            @Override
038            public void mousePressed(MouseEvent e) {
039                if (!SwingUtilities.isLeftMouseButton(e)) {
040                    return;
041                }
042                if (check instanceof QuadStateCheckBox) {
043                    ((QuadStateCheckBox) check).nextState();
044                } else {
045                    check.setSelected(!check.isSelected());
046                }
047            }
048        });
049
050        return panel;
051    }
052}