×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Hani Ibrahim
Added: Dec 30, 2016 2:02 AM
Modified: Feb 2, 2017 9:11 AM
Views: 9
Tags: preferences
Save jframe size and positions and center jframe on screen by default. Use with snippet "Store/Load preferences at startup and shutdown"
  1.     private void storePrefs() throws BackingStoreException {
  2.         // Get node
  3.         Preferences prefs = Preferences.userNodeForPackage(getClass());
  4.  
  5.         // Save window position
  6.         prefs.putInt("xpos", getLocation().x);
  7.         prefs.putInt("ypos", getLocation().y);
  8.  
  9.         // Save Window size
  10.         prefs.putInt("width", getSize().width);
  11.         prefs.putInt("height", getSize().height);
  12.  
  13.         prefs.flush(); // Made sure that all preferences are stored
  14.     }
  15.  
  16.     private void setPrefs() {
  17.         // Get node
  18.         Preferences prefs = Preferences.userNodeForPackage(getClass());
  19.  
  20.         // Calculate screen-centered windows position
  21.         final Dimension d = this.getToolkit().getScreenSize();
  22.         int win_x = (int) ((d.getWidth() - this.getWidth()) / 2);
  23.         int win_y = (int) ((d.getHeight() - this.getHeight()) / 2);
  24.  
  25.         // Set window position
  26.         setLocation(prefs.getInt("xpos", win_x),
  27.                 prefs.getInt("ypos", win_y));
  28.  
  29.         // Set window size
  30.         setSize(prefs.getInt("width", 637),
  31.                 prefs.getInt("height", 380));
  32.     }