View Javadoc
1   package com.nilhcem.fakesmtp.gui;
2   
3   import java.awt.Component;
4   import java.io.File;
5   import java.util.Observable;
6   import java.util.Observer;
7   import javax.swing.JFileChooser;
8   import com.nilhcem.fakesmtp.core.Configuration;
9   import com.nilhcem.fakesmtp.core.I18n;
10  import com.nilhcem.fakesmtp.gui.info.SaveMsgField;
11  import com.nilhcem.fakesmtp.model.UIModel;
12  
13  /**
14   * Provides a graphical directory chooser dialog.
15   * <p>
16   * The directory chooser is used to select the folder where emails will be saved in.<br>
17   * It can be launched from the menu bar, or from the main panel.
18   * </p>
19   *
20   * @author Nilhcem
21   * @since 1.0
22   */
23  public final class DirChooser extends Observable implements Observer {
24  
25  	private final JFileChooser dirChooser = new JFileChooser();
26  	private Component parent = null;
27  
28  	/**
29  	 * Creates a {@code JFileChooser} component and sets it to be for directories only.
30  	 *
31  	 * @param parent the component from where the chooser will be launched <i>(should be the main panel of the application)</i>.
32  	 */
33  	public DirChooser(Component parent) {
34  		this.parent = parent;
35  		dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
36  		dirChooser.setDialogTitle(String.format(I18n.INSTANCE.get("dirchooser.title"),
37  			Configuration.INSTANCE.get("application.name")));
38  		dirChooser.setApproveButtonText(I18n.INSTANCE.get("dirchooser.approve.btn"));
39  	}
40  
41  	/**
42  	 * Opens the folder selection.
43  	 * <p>
44  	 * This method will be called by an {@code Observable} element:
45       * </p>
46  	 * <ul>
47  	 *   <li>The {@link MenuBar};</li>
48  	 *   <li>Or the {@link SaveMsgField}.</li>
49  	 * </ul>
50  	 *
51  	 * @param o the observable element which will notify this class.
52  	 * @param arg optional parameters (not used).
53  	 */
54  	@Override
55  	public void update(Observable o, Object arg) {
56  		if (o instanceof MenuBar || o instanceof SaveMsgField) {
57  			openFolderSelection();
58  		}
59  	}
60  
61  	/**
62  	 * Opens the folder selection dialog and notify observers once the directory is selected.
63  	 * <p>
64  	 * The only observer notified is the {@link SaveMsgField}.
65  	 * </p>
66  	 */
67  	private void openFolderSelection() {
68  		File filePath = new File(Configuration.INSTANCE.get("emails.default.dir"));
69  		dirChooser.setCurrentDirectory(filePath);
70  
71  		int result = dirChooser.showOpenDialog(parent);
72  
73  		if (result == JFileChooser.APPROVE_OPTION) {
74  			File selectedDir = dirChooser.getSelectedFile();
75  			if (selectedDir != null) {
76  				UIModel.INSTANCE.setSavePath(selectedDir.getAbsolutePath());
77  				setChanged();
78  				notifyObservers();
79  			}
80  		}
81  	}
82  }