Java by API/java.util.prefs/PreferenceChangeEvent

Материал из Java эксперт
Перейти к: навигация, поиск

PreferenceChangeEvent: getKey()

 
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
public class Main implements PreferenceChangeListener {
  private Preferences userPrefs;
  public static final String NAMEPREF = "name";
  public static final String EMAILPREF = "email";
  public static void main(String args[]) {
    new Main();
  }
  public Main() {
    userPrefs = Preferences.userNodeForPackage(Main.class);
    System.out.println(userPrefs.get(NAMEPREF, ""));
    System.out.println(userPrefs.get(EMAILPREF, ""));
    userPrefs.put(NAMEPREF, "name");
    userPrefs.put(EMAILPREF, "email");
    Preferences.userNodeForPackage(Main.class).addPreferenceChangeListener(this);
  }
  public void preferenceChange(PreferenceChangeEvent evt) {
    String key = evt.getKey();
    String val = evt.getNewValue();
    if (key.equals(NAMEPREF)) {
      System.out.println(val);
    } else if (key.equals(EMAILPREF)) {
      System.out.println(val);
    }
  }
}





PreferenceChangeEvent: getNewValue()

 
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
public class Main implements PreferenceChangeListener {
  private Preferences userPrefs;
  public static final String NAMEPREF = "name";
  public static final String EMAILPREF = "email";
  public static void main(String args[]) {
    new Main();
  }
  public Main() {
    userPrefs = Preferences.userNodeForPackage(Main.class);
    System.out.println(userPrefs.get(NAMEPREF, ""));
    System.out.println(userPrefs.get(EMAILPREF, ""));
    userPrefs.put(NAMEPREF, "name");
    userPrefs.put(EMAILPREF, "email");
    Preferences.userNodeForPackage(Main.class).addPreferenceChangeListener(this);
  }
  public void preferenceChange(PreferenceChangeEvent evt) {
    String key = evt.getKey();
    String val = evt.getNewValue();
    if (key.equals(NAMEPREF)) {
      System.out.println(val);
    } else if (key.equals(EMAILPREF)) {
      System.out.println(val);
    }
  }
}