⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cbsaveloadtemplate.java

📁 JAVA开源LDAP浏览器jxplorer的源码!
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package com.ca.commons.cbutil;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * An object of this cunning class can be added as is
 * to any container containing user-input components
 * such as text fields, check boxes and so forth.  When
 * it is asked to 'save' a template, it scans through
 * its parent container, identifies user-input
 * components, and saves their data to a properties file
 * with the name 'template name' + 'component number'.These
 * can be automatically read back later.<p>
 * <p/>
 * At the moment it only handles the *swing* components: <br>
 * JTextField, CBJComboBox, JCheckBox, but it could easily be modified
 * (would need to change JContainer checks to Container).<p>
 * <p/>
 * It will iterate through sub-components, but since there is no
 * "JContainer" class, all sub-components must be explicitly listed
 * in the code; at the moment it only handles JPanel.<p>
 * The fact that it
 * does not handle JPasswordField is considered a feature.<p>
 * <p/>
 * <b>Warning</b> This class is unlikely to correctly handle
 * non-string data; i.e. combo boxes with icons etc.
 */

public class CBSaveLoadTemplate extends JPanel
{
    protected CBButton save, delete, makeDefault;
    protected CBJComboBox loadops;

    //public String saveFileName;    // the name of the properties file
    public Properties templates;   // the properties object, read from the file
//    String localDir;        // the local directory the properties file is stored in.
    String configFile;             // the config file where we load and save stuff...

    int numTemplates;       // the number of options saved in the properties file.

    private boolean saveFlag = false;	//TE: flag to show when the user has saved...used to stop the auto update of fields.

    Vector illegalComponents = new Vector(); // components that are specifically not to be messed with.

    static final String NUMTEMPLATES = "number_of_templates";
    static final String TEMPLATENAME = "template_name";
    static final String DEFAULT = "default";

    private static Logger log = Logger.getLogger(CBSaveLoadTemplate.class.getName());

    /**
     * Each CBSaveLoadTemplate object must have a file name to
     * read and load data from...
     */

    public CBSaveLoadTemplate(String fileName)
    {
        save = new CBButton(CBIntText.get("Save"), CBIntText.get("Click here to save current settings."));
        makeDefault = new CBButton(CBIntText.get("Default"), CBIntText.get("Click here to make the current setting the default."));
        delete = new CBButton(CBIntText.get("Delete"), CBIntText.get("Click here to delete a previously saved setting."));
        loadops = new CBJComboBox();
        templates = new Properties();

        configFile = parseFile(fileName);

        CBPanel main = new CBPanel();

        main.add(save);
        main.makeHeavy();
        main.add(loadops);
        main.makeLight();
        main.add(delete);
        main.add(makeDefault);

        setBorder(new TitledBorder(CBIntText.get(" Use a Template ")));
        setLayout(new BorderLayout());
        add(main);

        save.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                saveFlag = true;
                save();
            }
        });

        loadops.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (!saveFlag)							//TE: don't update fields if user has just saved.
                    load();
                saveFlag = false;
            }
        });
        loadops.setToolTipText(CBIntText.get("Click here to load a previously saved setting."));

        delete.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                int response = showMessage();

                if (response != JOptionPane.YES_OPTION)	//TE: delete confirmation dialog.
                    return;

                delete();
            }
        });

        makeDefault.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                makeDefault();
            }
        });
    }


    /**
     * Expose the root combo box for the use of adding listeners 'n stuff.
     */

    public CBJComboBox getLoadComboBox()
    {
        return loadops;
    }

    public CBButton getSaveButton()
    {
        return save;
    }

    /**
     * Opens an dialog that asks if the user wants to delete the template.
     *
     * @return the user response as an integer (see JOptionPane)
     */

    public int showMessage()
    {
        return JOptionPane.showConfirmDialog(this, CBIntText.get("Are you sure you want to delete the template?"),
                CBIntText.get("Delete Confirmation"), JOptionPane.YES_NO_OPTION);
    }


    /**
     * Loads the dafault set up (if one has been saved).
     * - equivalent to manually loading the template
     * named 'default'.
     */
    public void loadDefault()
    {
        String defaultName = templates.getProperty(DEFAULT);
        if ((defaultName != null) && (defaultName.length() != 0))
            loadTemplateName(defaultName);
    }


    /*
     *    parses a file and loads the data into a Properties object,
     *    and then into the loadops combo box.
     *    Returns the full path of the config file.
     */

    protected String parseFile(String fileName)
    {
        String configFile = CBUtility.getPropertyConfigPath(fileName);
        if (configFile == null)
        {
            CBUtility.error(this, "Unable to read user home directory ", null);
            return fileName;
        }

        templates = CBUtility.readPropertyFile(configFile);
        if (templates.size() == 0)
        {
            log.info("Initialising config file: " + configFile);
            return configFile;
        }

        String temp = templates.getProperty(NUMTEMPLATES);
        if (temp == null)
        {
            CBUtility.error(this, "Unable to read number of templates paramater from: " + configFile, null);
            return configFile;
        }


        numTemplates = Integer.parseInt(temp);

        for (int i = 0; i < numTemplates; i++)
        {
            temp = templates.getProperty(TEMPLATENAME + i);
            loadops.addItem(temp);
        }
        // make sure the default option is currently shown by the combo box.
        String defaultName = templates.getProperty(DEFAULT);
        loadops.setSelectedItem(defaultName);

        return configFile;
    }

    public String getCurrentTemplateName()
    {
        String currentTemplateName = (String) loadops.getSelectedItem();
        if (currentTemplateName == null) return "";
        return currentTemplateName;
    }

    /**
     * saves a dialog windows state by working through all the
     * components held by the parent container, and if they are
     * (selected) User Input objects (TextFields etc.) saving
     * their contents to a properties list.
     */

    public void save()
    {
        String currentTemplateName = getCurrentTemplateName();
        String templateName = (String) JOptionPane.showInputDialog(this, CBIntText.get("Enter template name") + ":", CBIntText.get("Replace/Create Template"), JOptionPane.QUESTION_MESSAGE, null, null, currentTemplateName);
        if (templateName == null) return; // user cancelled.
        saveTemplateName(templateName);
        loadops.setSelectedItem(templateName);		//TE: make sure the saved template is the current selection in the combo box.
    }

    public void saveTemplateName(String templateName)
    {
        templateName = templateName.replace('.', '-');  // el hack.  We use dots to do magic with... so bar user from using them and hope no-one ever notices...
        if (templateName == null) return; // user selected 'cancel'
        Container parent = getParent();
        saveContainerInfo(parent, templateName);  // save parent container

        /*
         *    Use a brute-force search to discover if we already have
         *    a template with the newly entered name (i.e. user is
         *    updating an existing entry) by iterating through all
         *    template name properties until we find a matching one (or not).
         */
        boolean we_already_got_one = false;
        for (int i = 0; i < numTemplates; i++)
        {
            String test = (String) templates.getProperty(TEMPLATENAME + i);
            if ((test != null) && (test.equals(templateName)))
            {
                we_already_got_one = true;
                break;
            }
        }

        if (we_already_got_one == false)
        {
            templates.setProperty(TEMPLATENAME + numTemplates, templateName);
            numTemplates++;
            templates.setProperty(NUMTEMPLATES, Integer.toString(numTemplates));
            loadops.addItem(templateName);
        }

        CBUtility.writePropertyFile(configFile, templates, "");

    }

    /**
     * iterates through a container, saving user-entry components as it goes.
     *
     * @param myContainer  container to save
     * @param templateName unique name for this template and component
     */

    public void saveContainerInfo(Container myContainer, String templateName)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -