Question

I'm trying to add an options menu to my program, with the options changeable using JCheckBoxMenuItems. Whatever the value of these options is will be saved to a file when the program closes. The file will be read when the program starts and the values set to the boolean read in. (ie. a check mark appears next to an item if the value read in is true, and one isn't there if the value is false).

This is what I have so far:

boolean soundEnabled = true;

JMenu fmOptionsMenu = new JMenu("Options");
    fileMenu.add(fmOptionsMenu);

    JCheckBoxMenuItem omSoundEnable = new JCheckBoxMenuItem("Enable Sound");
    omSoundEnable.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent arg0) {
            soundEnabled = !soundEnabled;
        }
    });
    fmOptionsMenu.add(omSoundEnable);

How can I set the default values, and is a PropertyChangeListener the correct one to use?

Was it helpful?

Solution

Whatever the value of these options is will be saved to a file when the program closes. The file will be read when the program starts and the values set to the boolean read in. (ie. a check mark appears next to an item if the value read in is true, and one isn't there if the value is false).

  • use JCheckBoxMenuItem.setSelected(boolean b), isSelected()

  • setSelected before any of Listener added to JCheckBoxMenuItem, because PropertyChangeListener can firing an proper event from propertyChange in the case that value is sets later, sure depends of what do you really want to do

  • I'm would be used Swing Action, ItemListener, ActionListener for JButtonComponents

OTHER TIPS

How can I set the default values

You can use a Properties file to store the default values.

PropertyChangeListener the correct one to use?

When the program closes you can just query the current state of each component and then save the value in the Properties file.

Use java.util.Preferences to persist the soundEnabled state; a complete example is cited here. In outline,

  • Define the default initial state:

    private static final boolean DEFAULT_SOUND_ENABLED = true;
    
  • Instantiate Preferences:

    Preferences p = Preferences.userRoot().node("org").node("foo").node("Bar");
    
  • Get the preferred state, or the defined default:

    public static boolean getSoundEnabled() {
        return p.getBoolean("soundEnabled", DEFAULT_SOUND_ENABLED);
    }
    ...
    private boolean soundEnabled = getSoundEnabled();
    
  • Store a new value, called from the menu's listener:

    public static void putSoundEnabled(boolean soundEnabled) {
        p.putBoolean("soundEnabled", soundEnabled);
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top