001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import java.awt.event.ActionEvent;
005
006import javax.swing.JCheckBoxMenuItem;
007
008import org.openstreetmap.josm.data.Preferences;
009import org.openstreetmap.josm.data.preferences.BooleanProperty;
010import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent;
011import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener;
012
013/**
014 * User action to toggle a custom boolean preference value.
015 *
016 * A user action will just change a preference value. To take any real action,
017 * register another {@link PreferenceChangedListener} for the given preference key.
018 */
019public class PreferenceToggleAction extends JosmAction implements PreferenceChangedListener {
020
021    private final JCheckBoxMenuItem checkbox;
022    private final BooleanProperty pref;
023
024    /**
025     * Create a new PreferenceToggleAction.
026     * @param name the (translated) title
027     * @param tooltip tooltip text
028     * @param prefKey the preference key to toggle
029     * @param prefDefault default value for the preference entry
030     */
031    public PreferenceToggleAction(String name, String tooltip, String prefKey, boolean prefDefault) {
032        super(name, null, tooltip, null, false);
033        putValue("toolbar", "toggle-" + prefKey);
034        this.pref = new BooleanProperty(prefKey, prefDefault);
035        checkbox = new JCheckBoxMenuItem(this);
036        checkbox.setSelected(pref.get());
037        Preferences.main().addWeakKeyPreferenceChangeListener(prefKey, this);
038    }
039
040    @Override
041    public void actionPerformed(ActionEvent e) {
042        pref.put(checkbox.isSelected());
043    }
044
045    /**
046     * Get the checkbox that can be used for this action. It can only be used at one place.
047     * @return The checkbox.
048     */
049    public JCheckBoxMenuItem getCheckbox() {
050        return checkbox;
051    }
052
053    @Override
054    public void preferenceChanged(PreferenceChangeEvent e) {
055        checkbox.setSelected(pref.get());
056    }
057}