001package jmri.util.swing;
002
003import java.util.*;
004
005import javax.swing.*;
006import javax.swing.event.ChangeEvent;
007
008import org.slf4j.Logger;
009import org.slf4j.LoggerFactory;
010
011/**
012 * Default swing behaviour is to close a JCheckBoxMenuItem when clicked. This
013 * leaves the menu open following a selection. Used when long lists are
014 * displayed.
015 * Does not stay open with Nimbus LAF Popup Menus,
016 * does stay open with other Nimbus LAF Menus.
017 * 
018 * @author Steve Young (C) 2019
019 */
020public class StayOpenCheckBoxItem extends JCheckBoxMenuItem {
021
022    private MenuElement[] path;
023
024    public StayOpenCheckBoxItem(String text) {
025        super(text);
026        initUI();
027    }
028    
029    public StayOpenCheckBoxItem(String text, boolean isSelected) {
030        super(text, isSelected);
031        initUI();
032    }
033    
034    private void initUI(){
035        putClientProperty("CheckBoxMenuItem.doNotCloseOnMouseClick", Boolean.TRUE);
036        if (useWithLAF()){
037            setUI(new StayOpenCheckBoxMenuItemUI());
038            getModel().addChangeListener((ChangeEvent e) -> {
039                if (getModel().isArmed() && isShowing()) {
040                    path = MenuSelectionManager.defaultManager().getSelectedPath();
041                }
042            });
043        }
044    }
045    
046    private static final Set<String> LAFS = new HashSet<String>(Arrays.asList(
047        new String[] {"Nimbus","Mac OS X"}));
048    
049    private static boolean useWithLAF() {
050        String laf = UIManager.getLookAndFeel().getName();
051        log.debug("Using LAF '{}'",laf);
052        return !LAFS.contains(laf);
053    }
054
055    @Override
056    public void doClick(int pressTime) {
057        super.doClick(pressTime);
058        if (useWithLAF()){
059            MenuSelectionManager.defaultManager().setSelectedPath(path);
060        }
061    }
062
063    private final static Logger log = LoggerFactory.getLogger(StayOpenCheckBoxItem.class);
064}